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

/**
 * Flag walk-in (instant-booking) queries. A quick booking still needs a
 * query row to hold the trip's basic details (guest / dates /
 * destination live on the query, not the booking — booking.query_id is
 * NOT NULL), but that query never went through the sales pipeline. It
 * was auto-stamped `stage = converted`, which inflated the Queries list
 * and the "converted" query counts on the dashboard.
 *
 * `is_walk_in = true` marks these so query-centric lists and counts can
 * exclude them, while they still back a real booking everywhere a
 * booking is counted. Existing walk-in queries (those with a
 * quick-booking) are back-filled so historical reports clean up too.
 */
export class QueryIsWalkIn1787600000000 implements MigrationInterface {
  name = 'QueryIsWalkIn1787600000000';

  public async up(qr: QueryRunner): Promise<void> {
    await qr.query(`
      ALTER TABLE "queries"
        ADD COLUMN IF NOT EXISTS "is_walk_in" boolean NOT NULL DEFAULT false
    `);
    // Back-fill: any query that backs a quick booking is a walk-in.
    await qr.query(`
      UPDATE "queries" q
         SET "is_walk_in" = true
        FROM "bookings" b
       WHERE b."query_id" = q."id"
         AND b."is_quick_booking" = true
         AND b."is_deleted" = false
         AND q."is_walk_in" = false
    `);
  }

  public async down(qr: QueryRunner): Promise<void> {
    await qr.query(`
      ALTER TABLE "queries"
        DROP COLUMN IF EXISTS "is_walk_in"
    `);
  }
}
