import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddProcurement1980000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.vendors (
        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,
        name varchar NOT NULL,
        type varchar,
        contact_person varchar,
        phone varchar,
        email varchar,
        address varchar,
        is_active boolean NOT NULL DEFAULT true
      );
    `);

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.asset_acquisitions (
        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,
        vendor_id uuid,
        acquisition_type varchar NOT NULL,
        acquisition_date date NOT NULL,
        cost numeric(14,2),
        useful_life_months integer,
        salvage_value numeric(14,2),
        lease_start date,
        lease_end date,
        monthly_payment numeric(14,2),
        status varchar NOT NULL DEFAULT 'ACTIVE',
        notes text
      );
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_asset_acquisitions_vehicle_date
        ON freight.asset_acquisitions(vehicle_id, acquisition_date);
    `);

    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.asset_disposals (
        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 NOT NULL,
        disposal_date date NOT NULL,
        method varchar NOT NULL,
        sale_price numeric(14,2),
        buyer varchar,
        notes text
      );
    `);

    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_asset_disposals_vehicle_date
        ON freight.asset_disposals(vehicle_id, disposal_date);
    `);
  }

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