import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Supplier Collection — dedicated permission module for the read-only
 * supplier/driver cash-at-service rollup page (GET /by-supplier, GET
 * /by-supplier/drivers). Split from PAYMENT_COLLECTION so admins can
 * grant listing access without MD mark-required / confirm / amend rights.
 *
 * Seeds every existing role at `none`; Admin gets `delete` so the page
 * is usable immediately. Ops can upgrade other roles from Settings → Roles.
 *
 * Companion: ModuleName.SUPPLIER_COLLECTION in role-permission.entity.ts.
 * New tenants also pick up rows via tenant.service.ts onModuleInit backfill.
 */
export class SupplierCollectionPermission1785500000000 implements MigrationInterface {
  name = 'SupplierCollectionPermission1785500000000';

  public async up(qr: QueryRunner): Promise<void> {
    await qr.query(`
      INSERT INTO "role_permissions" ("id", "tenant_id", "role_id", "module", "access_level", "created_at", "updated_at", "is_deleted")
      SELECT
        gen_random_uuid(),
        r."tenant_id",
        r."id",
        'supplier_collection',
        'none',
        NOW(),
        NOW(),
        false
      FROM "roles" r
      WHERE r."is_deleted" = false
        AND NOT EXISTS (
          SELECT 1 FROM "role_permissions" rp
          WHERE rp."role_id" = r."id"
            AND rp."module" = 'supplier_collection'
        )
    `);

    await qr.query(`
      UPDATE "role_permissions"
      SET "access_level" = 'delete', "updated_at" = NOW()
      WHERE "module" = 'supplier_collection'
        AND "role_id" IN (
          SELECT "id" FROM "roles"
          WHERE "is_deleted" = false
            AND "is_system" = true
            AND LOWER("name") = 'admin'
        )
    `);

    // Operations-facing roles get VIEW by default so the listing is
    // available without a manual Settings pass after deploy.
    await qr.query(`
      UPDATE "role_permissions"
      SET "access_level" = 'view', "updated_at" = NOW()
      WHERE "module" = 'supplier_collection'
        AND "role_id" IN (
          SELECT "id" FROM "roles"
          WHERE "is_deleted" = false
            AND "is_system" = true
            AND LOWER("name") IN (
              'operations manager',
              'trip coordinator',
              'transport manager',
              'activity manager'
            )
        )
    `);
  }

  public async down(qr: QueryRunner): Promise<void> {
    await qr.query(`
      DELETE FROM "role_permissions"
      WHERE "module" = 'supplier_collection'
    `);
  }
}
