/**
 * Migration: Create Ports Table
 */

import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Create ports table
    await queryRunner.query(`
      CREATE TABLE "ports" (
        "id" UUID NOT NULL DEFAULT uuid_generate_v4(),
        "code" CHAR(5) NOT NULL,
        "name" VARCHAR(255) NOT NULL,
        "city" VARCHAR(255) NOT NULL,
        "country" CHAR(2) NOT NULL,
        "country_name" VARCHAR(100) NOT NULL,
        "latitude" DECIMAL(9,6) NOT NULL,
        "longitude" DECIMAL(9,6) NOT NULL,
        "timezone" VARCHAR(50) NULL,
        "is_active" BOOLEAN NOT NULL DEFAULT TRUE,
        "created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        "updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        CONSTRAINT "pk_ports" PRIMARY KEY ("id"),
        CONSTRAINT "uq_ports_code" UNIQUE ("code"),
        CONSTRAINT "chk_ports_code" CHECK ("code" ~ '^[A-Z0-9]{5}$'),
        CONSTRAINT "chk_ports_country" CHECK ("country" ~ '^[A-Z]{2}$'),
        CONSTRAINT "chk_ports_latitude" CHECK ("latitude" >= -90 AND "latitude" <= 90),
        CONSTRAINT "chk_ports_longitude" CHECK ("longitude" >= -180 AND "longitude" <= 180)
      )
    `);

    // Create indexes
    await queryRunner.query(`
      CREATE INDEX "idx_ports_code" ON "ports" ("code")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_ports_country" ON "ports" ("country")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_ports_active" ON "ports" ("is_active")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_ports_coordinates" ON "ports" ("latitude", "longitude")
    `);

    // Create GIN indexes for fuzzy search using pg_trgm
    await queryRunner.query(`
      CREATE INDEX "idx_ports_name_trgm" ON "ports" USING GIN ("name" gin_trgm_ops)
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_ports_city_trgm" ON "ports" USING GIN ("city" gin_trgm_ops)
    `);

    // Add comments
    await queryRunner.query(`
      COMMENT ON TABLE "ports" IS 'Maritime ports (UN/LOCODE standard)'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "ports"."code" IS 'UN/LOCODE (5 characters: CC + LLL)'
    `);
  }

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