/**
 * Migration: Create Carriers Table
 */

import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Create carriers table
    await queryRunner.query(`
      CREATE TABLE "carriers" (
        "id" UUID NOT NULL DEFAULT uuid_generate_v4(),
        "name" VARCHAR(255) NOT NULL,
        "code" VARCHAR(50) NOT NULL,
        "scac" CHAR(4) NOT NULL,
        "logo_url" TEXT NULL,
        "website" TEXT NULL,
        "api_config" JSONB NULL,
        "is_active" BOOLEAN NOT NULL DEFAULT TRUE,
        "supports_api" BOOLEAN NOT NULL DEFAULT FALSE,
        "created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        "updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        CONSTRAINT "pk_carriers" PRIMARY KEY ("id"),
        CONSTRAINT "uq_carriers_code" UNIQUE ("code"),
        CONSTRAINT "uq_carriers_scac" UNIQUE ("scac"),
        CONSTRAINT "chk_carriers_code" CHECK ("code" ~ '^[A-Z_]+$'),
        CONSTRAINT "chk_carriers_scac" CHECK ("scac" ~ '^[A-Z]{4}$')
      )
    `);

    // Create indexes
    await queryRunner.query(`
      CREATE INDEX "idx_carriers_code" ON "carriers" ("code")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_carriers_scac" ON "carriers" ("scac")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_carriers_active" ON "carriers" ("is_active")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_carriers_supports_api" ON "carriers" ("supports_api")
    `);

    // Add comments
    await queryRunner.query(`
      COMMENT ON TABLE "carriers" IS 'Shipping carriers with API configuration'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "carriers"."api_config" IS 'API configuration (baseUrl, credentials, timeout, etc.)'
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE "carriers"`);
  }
}
