import { sequelize } from '@config/database';
import logger from '@utils/logger';

/**
 * Ensures CPC-CSD tables exist (idempotent). Runs at app startup so a fresh DB
 * still serves CPC routes even if the migrations runner was skipped once.
 */
export async function ensureCpcCdcSchema(): Promise<void> {
  try {
    await 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 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 sequelize.query(`DROP INDEX IF EXISTS unique_cpc_document_attempt;`);
    await sequelize.query(`
      CREATE UNIQUE INDEX IF NOT EXISTS unique_cpc_document_claim_attempt_booking
      ON cpc_documents (claim_id, attempt_no, booking_id);
    `);

    logger.info('[CPC-CSD] Schema check complete (cpc_documents / cpc_audit_logs).');
  } catch (err) {
    logger.error('[CPC-CSD] ensureCpcCdcSchema failed — run `npm run migrate` in re-workflow-be.', err);
    // Do not block app boot; CPC routes will error until DB is fixed.
  }
}
