import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Accident & Incident register for the fleet. Tracks accidents, breakdowns,
 * traffic violations, thefts and other incidents against a vehicle, driver
 * and/or booking, with severity, damage estimate, insurance claim tracking and
 * a lifecycle status. Queried by driver_id for per-driver incident history.
 */
export class AddIncidents1960000000000 implements MigrationInterface {
  name = 'AddIncidents1960000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.incidents (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        created_at timestamptz NOT NULL DEFAULT now(),
        updated_at timestamptz NOT NULL DEFAULT now(),
        deleted_at timestamptz,
        vehicle_id uuid,
        driver_id uuid,
        booking_id uuid,
        type varchar NOT NULL,
        severity varchar NOT NULL,
        occurred_at timestamptz NOT NULL,
        location varchar,
        description text NOT NULL,
        damage_estimate numeric(14,2),
        status varchar NOT NULL DEFAULT 'REPORTED',
        insurance_claim_number varchar,
        reported_by varchar
      )
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_INCIDENTS_DRIVER"
      ON freight.incidents (driver_id, occurred_at)
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_INCIDENTS_VEHICLE"
      ON freight.incidents (vehicle_id, occurred_at)
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE IF EXISTS freight.incidents`);
  }
}
