import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * Append-only audit log for fleet activity (driver↔vehicle assignments, vehicle
 * status/availability transitions, first/last-mile vehicle assignments + mile
 * status changes). Queried by vehicle_id or driver_id to build a per-record
 * timeline. Populated going forward — existing records have no back-history.
 */
export class AddFleetEvents1890000000008 implements MigrationInterface {
  name = "AddFleetEvents1890000000008";

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.fleet_events (
        id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
        event_type varchar NOT NULL,
        vehicle_id uuid,
        driver_id uuid,
        first_mile_id uuid,
        last_mile_id uuid,
        from_value varchar,
        to_value varchar,
        label varchar,
        metadata jsonb,
        created_at timestamptz NOT NULL DEFAULT now(),
        updated_at timestamptz NOT NULL DEFAULT now(),
        deleted_at timestamptz
      )
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_FLEET_EVENTS_VEHICLE"
      ON freight.fleet_events (vehicle_id, created_at)
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "IDX_FLEET_EVENTS_DRIVER"
      ON freight.fleet_events (driver_id, created_at)
    `);
  }

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