/**
 * Migration: Create PostgreSQL Extensions and Organizations Table
 */

import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Create extensions
    await queryRunner.query(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`);
    await queryRunner.query(`CREATE EXTENSION IF NOT EXISTS "pg_trgm"`);

    // Create organizations table
    await queryRunner.query(`
      CREATE TABLE "organizations" (
        "id" UUID NOT NULL DEFAULT uuid_generate_v4(),
        "name" VARCHAR(255) NOT NULL,
        "type" VARCHAR(50) NOT NULL,
        "scac" CHAR(4) NULL,
        "address_street" VARCHAR(255) NOT NULL,
        "address_city" VARCHAR(100) NOT NULL,
        "address_state" VARCHAR(100) NULL,
        "address_postal_code" VARCHAR(20) NOT NULL,
        "address_country" CHAR(2) NOT NULL,
        "logo_url" TEXT NULL,
        "documents" JSONB NOT NULL DEFAULT '[]',
        "is_active" BOOLEAN NOT NULL DEFAULT TRUE,
        "created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        "updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        CONSTRAINT "pk_organizations" PRIMARY KEY ("id"),
        CONSTRAINT "uq_organizations_name" UNIQUE ("name"),
        CONSTRAINT "uq_organizations_scac" UNIQUE ("scac"),
        CONSTRAINT "chk_organizations_scac_format" CHECK ("scac" IS NULL OR "scac" ~ '^[A-Z]{4}$'),
        CONSTRAINT "chk_organizations_country" CHECK ("address_country" ~ '^[A-Z]{2}$')
      )
    `);

    // Create indexes
    await queryRunner.query(`
      CREATE INDEX "idx_organizations_type" ON "organizations" ("type")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_organizations_scac" ON "organizations" ("scac")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_organizations_active" ON "organizations" ("is_active")
    `);

    // Add comments
    await queryRunner.query(`
      COMMENT ON TABLE "organizations" IS 'Business organizations (freight forwarders, carriers, shippers)'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "organizations"."scac" IS 'Standard Carrier Alpha Code (4 uppercase letters, carriers only)'
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE "organizations"`);
    await queryRunner.query(`DROP EXTENSION IF EXISTS "pg_trgm"`);
    await queryRunner.query(`DROP EXTENSION IF EXISTS "uuid-ossp"`);
  }
}
