import { QueryInterface } from 'sequelize';

/**
 * Idempotent CPC-CDC schema for environments where 2026041300 did not run or tables were dropped.
 * Safe to run on top of an existing DB that already has these tables from the earlier migration.
 */
export async function up(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.sequelize.query(`
    CREATE TABLE IF NOT EXISTS cpc_documents (
      id UUID NOT NULL PRIMARY KEY,
      booking_id VARCHAR(255),
      claim_id VARCHAR(255),
      attempt_no INTEGER NOT NULL DEFAULT 1,
      document_type VARCHAR(255),
      document_gcp_url TEXT,
      provider VARCHAR(255),
      msd_payload JSONB,
      extracted_fields JSONB,
      field_confidence JSONB,
      validation_status VARCHAR(255),
      match_percentage DOUBLE PRECISION,
      mismatch_reasons JSONB,
      field_results JSONB,
      ip_address VARCHAR(255),
      created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
    );
  `);

  await queryInterface.sequelize.query(`
    CREATE TABLE IF NOT EXISTS cpc_audit_logs (
      id UUID NOT NULL PRIMARY KEY,
      document_id UUID NOT NULL REFERENCES cpc_documents(id) ON DELETE CASCADE,
      action VARCHAR(255) NOT NULL,
      previous_state JSONB,
      new_state JSONB,
      performed_by VARCHAR(255),
      remarks TEXT,
      created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
    );
  `);

  await queryInterface.sequelize.query(`
    CREATE UNIQUE INDEX IF NOT EXISTS unique_cpc_document_attempt
    ON cpc_documents (claim_id, attempt_no, booking_id);
  `);
}

export async function down(_queryInterface: QueryInterface): Promise<void> {
  // Non-destructive: tables may contain production CPC data.
}
