import { QueryInterface, DataTypes } from 'sequelize';

export async function up(queryInterface: QueryInterface): Promise<void> {
  // Create cpc_documents table
  await queryInterface.createTable('cpc_documents', {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
      allowNull: false
    },
    booking_id: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    claim_id: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    attempt_no: {
      type: DataTypes.INTEGER,
      defaultValue: 1,
      allowNull: false
    },
    document_type: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    document_gcp_url: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    provider: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    msd_payload: {
      type: DataTypes.JSONB,
      allowNull: true
    },
    extracted_fields: {
      type: DataTypes.JSONB,
      allowNull: true
    },
    field_confidence: {
      type: DataTypes.JSONB,
      allowNull: true
    },
    validation_status: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    match_percentage: {
      type: DataTypes.FLOAT,
      allowNull: true
    },
    mismatch_reasons: {
      type: DataTypes.JSONB,
      allowNull: true
    },
    field_results: {
      type: DataTypes.JSONB,
      allowNull: true
    },
    ip_address: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    created_at: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      allowNull: false
    }
  });

  // Create cpc_audit_logs table
  await queryInterface.createTable('cpc_audit_logs', {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
      allowNull: false
    },
    document_id: {
      type: DataTypes.UUID,
      allowNull: false,
      references: {
        model: 'cpc_documents',
        key: 'id'
      },
      onDelete: 'CASCADE'
    },
    action: {
      type: DataTypes.STRING(255),
      allowNull: false
    },
    previous_state: {
      type: DataTypes.JSONB,
      allowNull: true
    },
    new_state: {
      type: DataTypes.JSONB,
      allowNull: true
    },
    performed_by: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    created_at: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      allowNull: false
    }
  });

  // Unique index for the multi-attempt claim logic (idempotent for repeated startup migrations)
  await queryInterface.sequelize.query(`
    CREATE UNIQUE INDEX IF NOT EXISTS unique_cpc_document_attempt
    ON cpc_documents (claim_id, attempt_no, document_type);
  `);
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.dropTable('cpc_audit_logs');
  await queryInterface.dropTable('cpc_documents');
}
