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

/**
 * Quote-level tax configuration — drives the Markup panel's tax
 * column + final-price math. Independent of the per-line
 * `tax_breakdown` snapshots from migration 1777700000000:
 *   - per-line tax_breakdown   → invoice + audit (frozen rates)
 *   - quote/booking tax config → user's chosen slab + inclusive flag
 *                                for the markup-view presentation
 *
 * Columns added to query_quotes and bookings:
 *   tax_slab_id   uuid NULL — chosen slab (FK to tax_slabs); NULL = no tax
 *   tax_inclusive boolean   — true → totals already include tax
 *                             false → tax is added on top at final
 *
 * Both nullable / defaulted so existing rows continue to work.
 * Booking-create from quote copies the quote's choice forward.
 */
export class QuoteTaxConfig1777800000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `ALTER TABLE query_quotes ADD COLUMN IF NOT EXISTS tax_slab_id uuid NULL`,
    );
    await queryRunner.query(
      `ALTER TABLE query_quotes ADD COLUMN IF NOT EXISTS tax_inclusive boolean NOT NULL DEFAULT false`,
    );
    await queryRunner.query(`ALTER TABLE bookings ADD COLUMN IF NOT EXISTS tax_slab_id uuid NULL`);
    await queryRunner.query(
      `ALTER TABLE bookings ADD COLUMN IF NOT EXISTS tax_inclusive boolean NOT NULL DEFAULT false`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`ALTER TABLE bookings DROP COLUMN IF EXISTS tax_inclusive`);
    await queryRunner.query(`ALTER TABLE bookings DROP COLUMN IF EXISTS tax_slab_id`);
    await queryRunner.query(`ALTER TABLE query_quotes DROP COLUMN IF EXISTS tax_inclusive`);
    await queryRunner.query(`ALTER TABLE query_quotes DROP COLUMN IF EXISTS tax_slab_id`);
  }
}
