/**
 * Migration: Add Carrier Flag to Organizations
 *
 * Marks organizations as carriers (transporteurs) and tracks their specialization
 * Allows differentiation between client organizations and carrier organizations
 */

import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Add carrier-related columns to organizations
    await queryRunner.query(`
      ALTER TABLE "organizations"
      ADD COLUMN "is_carrier" BOOLEAN NOT NULL DEFAULT FALSE,
      ADD COLUMN "carrier_type" VARCHAR(50) NULL
    `);

    // Create index for is_carrier flag
    await queryRunner.query(`
      CREATE INDEX "idx_organizations_is_carrier" ON "organizations" ("is_carrier")
    `);

    // Composite index for carrier organizations by type
    await queryRunner.query(`
      CREATE INDEX "idx_organizations_carrier_type"
      ON "organizations" ("is_carrier", "carrier_type")
      WHERE "is_carrier" = TRUE
    `);

    // Add comments
    await queryRunner.query(`
      COMMENT ON COLUMN "organizations"."is_carrier" IS 'True if organization is a carrier (transporteur)'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "organizations"."carrier_type" IS 'Type: LCL, FCL, BOTH, NVOCC, FREIGHT_FORWARDER, etc.'
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Remove indexes first
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_organizations_is_carrier"`);
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_organizations_carrier_type"`);

    // Remove columns
    await queryRunner.query(`
      ALTER TABLE "organizations"
      DROP COLUMN IF EXISTS "is_carrier",
      DROP COLUMN IF EXISTS "carrier_type"
    `);
  }
}
