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

/**
 * Agent Cost master — name + percentage, one rule per trip source.
 *
 * Assignment is trip_sources.agent_cost_id, for every source type.
 * Delete of a rule that is still assigned
 * is blocked in the service; the FK is RESTRICT as a backstop.
 */
export class AgentCost1786800000000 implements MigrationInterface {
  name = 'AgentCost1786800000000';

  public async up(qr: QueryRunner): Promise<void> {
    await qr.query(`
      CREATE TABLE agent_costs (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        tenant_id uuid NOT NULL,
        name varchar(255) NOT NULL,
        percentage decimal(6,2) NOT NULL,
        is_active boolean NOT NULL DEFAULT true,
        is_deleted boolean NOT NULL DEFAULT false,
        created_by uuid,
        updated_by uuid,
        created_at timestamptz NOT NULL DEFAULT now(),
        updated_at timestamptz NOT NULL DEFAULT now(),
        CONSTRAINT chk_agent_costs_percentage
          CHECK (percentage > 0 AND percentage <= 999.99)
      );
    `);
    await qr.query(`
      CREATE INDEX idx_agent_costs_tenant_deleted
        ON agent_costs (tenant_id, is_deleted);
    `);
    await qr.query(`
      CREATE UNIQUE INDEX uq_agent_costs_tenant_name_active
        ON agent_costs (tenant_id, LOWER(name))
        WHERE is_deleted = false;
    `);

    await qr.query(`
      ALTER TABLE trip_sources
        ADD COLUMN agent_cost_id uuid NULL
          REFERENCES agent_costs(id) ON DELETE RESTRICT;
    `);
    await qr.query(`
      CREATE INDEX idx_trip_sources_agent_cost
        ON trip_sources (tenant_id, agent_cost_id)
        WHERE is_deleted = false AND agent_cost_id IS NOT NULL;
    `);
  }

  public async down(qr: QueryRunner): Promise<void> {
    await qr.query(`DROP INDEX IF EXISTS idx_trip_sources_agent_cost;`);
    await qr.query(`ALTER TABLE trip_sources DROP COLUMN IF EXISTS agent_cost_id;`);
    await qr.query(`DROP INDEX IF EXISTS uq_agent_costs_tenant_name_active;`);
    await qr.query(`DROP INDEX IF EXISTS idx_agent_costs_tenant_deleted;`);
    await qr.query(`DROP TABLE IF EXISTS agent_costs;`);
  }
}
