import { type MigrationInterface, type QueryRunner } from 'typeorm';

/**
 * Adds three new ChangeRequestKind enum values + seeds the new
 * `booking_approval_bypass` permission module on the Admin role of
 * every existing tenant.
 *
 * Kinds:
 *   - same_day_booking   → booking.start_date == today in dest tz
 *   - next_day_booking   → booking.start_date == today + 1 day
 *   - post_confirm_edit  → line-item edit on a confirmed/ongoing/
 *                          completed booking
 *
 * ⚠ `ALTER TYPE ... ADD VALUE` cannot run inside a transaction, so
 * the migration explicitly opts out via `transaction = false`. Same
 * pattern as 1777300000000-AddBelowFloorPriceCRKind.
 *
 * Permission seed idempotency: INSERT ... WHERE NOT EXISTS so
 * re-running (or running against tenants who already have the
 * permission) is a no-op.
 */
export class BookingApprovalTriggers1783800000000 implements MigrationInterface {
  transaction = false as const;

  public async up(qr: QueryRunner): Promise<void> {
    await qr.query(
      `ALTER TYPE "booking_change_requests_kind_enum" ADD VALUE IF NOT EXISTS 'same_day_booking'`,
    );
    await qr.query(
      `ALTER TYPE "booking_change_requests_kind_enum" ADD VALUE IF NOT EXISTS 'next_day_booking'`,
    );
    await qr.query(
      `ALTER TYPE "booking_change_requests_kind_enum" ADD VALUE IF NOT EXISTS 'post_confirm_edit'`,
    );

    // Seed booking_approval_bypass:view on the Admin role of every
    // tenant. Admin gets it by default; ops can extend to other roles
    // (e.g., a "Full-approval Ops Manager") via Settings → Roles.
    await qr.query(`
      INSERT INTO role_permissions
        (role_id, module, access_level, tenant_id, created_by, updated_by)
      SELECT
        r.id,
        'booking_approval_bypass',
        'view'::role_permissions_access_level_enum,
        r.tenant_id,
        NULL,
        NULL
      FROM roles r
      WHERE r.name = 'Admin'
        AND r.is_deleted = false
        AND NOT EXISTS (
          SELECT 1 FROM role_permissions rp
          WHERE rp.role_id = r.id
            AND rp.module = 'booking_approval_bypass'
            AND rp.is_deleted = false
        )
    `);
  }

  public async down(qr: QueryRunner): Promise<void> {
    // Enum values cannot be dropped in Postgres — leave the three
    // kinds in place. Only revert the permission seed.
    await qr.query(
      `DELETE FROM role_permissions WHERE module = 'booking_approval_bypass'`,
    );
  }
}
