/**
 * Migration: Add Password Protection to CSV Bookings
 *
 * Adds password protection for carrier document access
 * Including: booking_number (readable ID) and password_hash
 */

import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddPasswordToCsvBookings1738200000000 implements MigrationInterface {
  name = 'AddPasswordToCsvBookings1738200000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Add password-related columns to csv_bookings
    await queryRunner.query(`
      ALTER TABLE "csv_bookings"
      ADD COLUMN "booking_number" VARCHAR(20) NULL,
      ADD COLUMN "password_hash" TEXT NULL
    `);

    // Create unique index for booking_number
    await queryRunner.query(`
      CREATE UNIQUE INDEX "idx_csv_bookings_booking_number"
      ON "csv_bookings" ("booking_number")
      WHERE "booking_number" IS NOT NULL
    `);

    // Add comments
    await queryRunner.query(`
      COMMENT ON COLUMN "csv_bookings"."booking_number" IS 'Human-readable booking number (format: XPD-YYYY-XXXXXX)'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "csv_bookings"."password_hash" IS 'Argon2 hashed password for carrier document access'
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Remove index first
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_csv_bookings_booking_number"`);

    // Remove columns
    await queryRunner.query(`
      ALTER TABLE "csv_bookings"
      DROP COLUMN IF EXISTS "booking_number",
      DROP COLUMN IF EXISTS "password_hash"
    `);
  }
}
