import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.bookings
        ADD COLUMN IF NOT EXISTS contract_template_key VARCHAR(80),
        ADD COLUMN IF NOT EXISTS contract_generated_at TIMESTAMPTZ,
        ADD COLUMN IF NOT EXISTS pricing_breakdown JSONB;
    `);

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.booking_contract_signatures (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        booking_id UUID NOT NULL REFERENCES freight.bookings(id) ON DELETE CASCADE,
        signer_role VARCHAR(20) NOT NULL,
        signer_user_id UUID,
        signer_display_name VARCHAR(200) NOT NULL,
        signed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        signature_file_id UUID REFERENCES freight.files(id) ON DELETE SET NULL,
        consent_text TEXT,
        ip_address VARCHAR(64),
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        deleted_at TIMESTAMPTZ,
        CONSTRAINT uq_booking_contract_signatures_role
          UNIQUE (booking_id, signer_role)
      );
      CREATE INDEX IF NOT EXISTS idx_booking_contract_signatures_booking_id
        ON freight.booking_contract_signatures(booking_id);
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE IF EXISTS freight.booking_contract_signatures;`);
    await queryRunner.query(`
      ALTER TABLE freight.bookings
        DROP COLUMN IF EXISTS pricing_breakdown,
        DROP COLUMN IF EXISTS contract_generated_at,
        DROP COLUMN IF EXISTS contract_template_key;
    `);
  }
}
