/**
 * Migration: Create CSV Rate Configs Table
 *
 * Stores configuration mapping company names to CSV rate files
 * Used by CSV-based rate search system
 */

import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Create csv_rate_configs table
    await queryRunner.query(`
      CREATE TABLE "csv_rate_configs" (
        "id" UUID NOT NULL DEFAULT uuid_generate_v4(),
        "company_name" VARCHAR(255) NOT NULL,
        "csv_file_path" VARCHAR(500) NOT NULL,
        "type" VARCHAR(50) NOT NULL DEFAULT 'CSV_ONLY',
        "has_api" BOOLEAN NOT NULL DEFAULT FALSE,
        "api_connector" VARCHAR(100) NULL,
        "is_active" BOOLEAN NOT NULL DEFAULT TRUE,
        "uploaded_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        "uploaded_by" UUID NULL,
        "last_validated_at" TIMESTAMP NULL,
        "row_count" INTEGER NULL,
        "metadata" JSONB NULL,
        "created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        "updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        CONSTRAINT "pk_csv_rate_configs" PRIMARY KEY ("id"),
        CONSTRAINT "uq_csv_rate_configs_company" UNIQUE ("company_name"),
        CONSTRAINT "chk_csv_rate_configs_type" CHECK ("type" IN ('CSV_ONLY', 'CSV_AND_API'))
      )
    `);

    // Create indexes
    await queryRunner.query(`
      CREATE INDEX "idx_csv_rate_configs_company" ON "csv_rate_configs" ("company_name")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_csv_rate_configs_active" ON "csv_rate_configs" ("is_active")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_csv_rate_configs_has_api" ON "csv_rate_configs" ("has_api")
    `);

    // Add comments
    await queryRunner.query(`
      COMMENT ON TABLE "csv_rate_configs" IS 'Configuration for CSV-based shipping rate files'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "csv_rate_configs"."company_name" IS 'Carrier company name (must be unique)'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "csv_rate_configs"."csv_file_path" IS 'Relative path to CSV file from rates directory'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "csv_rate_configs"."type" IS 'Integration type: CSV_ONLY or CSV_AND_API'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "csv_rate_configs"."has_api" IS 'Whether company has API connector available'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "csv_rate_configs"."api_connector" IS 'Name of API connector class if has_api=true'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "csv_rate_configs"."row_count" IS 'Number of rate rows in CSV file'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "csv_rate_configs"."metadata" IS 'Additional metadata (validation results, etc.)'
    `);

    // Add foreign key to users table for uploaded_by
    await queryRunner.query(`
      ALTER TABLE "csv_rate_configs"
      ADD CONSTRAINT "fk_csv_rate_configs_user"
      FOREIGN KEY ("uploaded_by")
      REFERENCES "users"("id")
      ON DELETE SET NULL
    `);

    // Seed initial CSV rate configurations
    await queryRunner.query(`
      INSERT INTO "csv_rate_configs" (
        "company_name",
        "csv_file_path",
        "type",
        "has_api",
        "api_connector",
        "is_active",
        "metadata"
      ) VALUES
      (
        'SSC Consolidation',
        'ssc-consolidation.csv',
        'CSV_ONLY',
        FALSE,
        NULL,
        TRUE,
        '{"description": "SSC Consolidation LCL rates", "coverage": "Europe to US/Asia"}'::jsonb
      ),
      (
        'ECU Worldwide',
        'ecu-worldwide.csv',
        'CSV_AND_API',
        TRUE,
        'ecu-worldwide',
        TRUE,
        '{"description": "ECU Worldwide LCL rates with API fallback", "coverage": "Europe to US/Asia", "api_portal": "https://api-portal.ecuworldwide.com"}'::jsonb
      ),
      (
        'TCC Logistics',
        'tcc-logistics.csv',
        'CSV_ONLY',
        FALSE,
        NULL,
        TRUE,
        '{"description": "TCC Logistics LCL rates", "coverage": "Europe to US/Asia"}'::jsonb
      ),
      (
        'NVO Consolidation',
        'nvo-consolidation.csv',
        'CSV_ONLY',
        FALSE,
        NULL,
        TRUE,
        '{"description": "NVO Consolidation LCL rates", "coverage": "Europe to US/Asia", "note": "Netherlands-based NVOCC"}'::jsonb
      ),
      (
        'Test Maritime Express',
        'test-maritime-express.csv',
        'CSV_ONLY',
        FALSE,
        NULL,
        TRUE,
        '{"description": "Fictional carrier for testing comparator", "coverage": "Europe to US/Asia", "note": "10-20% cheaper pricing for testing purposes"}'::jsonb
      )
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Drop foreign key
    await queryRunner.query(`
      ALTER TABLE "csv_rate_configs" DROP CONSTRAINT "fk_csv_rate_configs_user"
    `);

    // Drop indexes
    await queryRunner.query(`
      DROP INDEX "idx_csv_rate_configs_has_api"
    `);
    await queryRunner.query(`
      DROP INDEX "idx_csv_rate_configs_active"
    `);
    await queryRunner.query(`
      DROP INDEX "idx_csv_rate_configs_company"
    `);

    // Drop table
    await queryRunner.query(`
      DROP TABLE "csv_rate_configs"
    `);
  }
}
