import { DataTypes, Model, Optional } from 'sequelize';
import { sequelize } from '@config/database';

interface CpcAuditLogAttributes {
  id: string;
  documentId: string;
  action: string;
  previousState?: any;
  newState?: any;
  performedBy?: string;
  remarks?: string;
  createdAt?: Date;
}

interface CpcAuditLogCreationAttributes extends Optional<CpcAuditLogAttributes, 'id' | 'createdAt'> {}

class CpcAuditLog extends Model<CpcAuditLogAttributes, CpcAuditLogCreationAttributes> implements CpcAuditLogAttributes {
  public id!: string;
  public documentId!: string;
  public action!: string;
  public previousState?: any;
  public newState?: any;
  public performedBy?: string;
  public remarks?: string;
  public createdAt!: Date;
}

CpcAuditLog.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
      field: 'id'
    },
    documentId: {
      type: DataTypes.UUID,
      allowNull: false,
      field: 'document_id',
      references: {
        model: 'cpc_documents',
        key: 'id'
      }
    },
    action: {
      type: DataTypes.STRING(255),
      allowNull: false
    },
    previousState: {
      type: DataTypes.JSONB,
      allowNull: true,
      field: 'previous_state'
    },
    newState: {
      type: DataTypes.JSONB,
      allowNull: true,
      field: 'new_state'
    },
    performedBy: {
      type: DataTypes.STRING(255),
      allowNull: true,
      field: 'performed_by'
    },
    remarks: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    createdAt: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      field: 'created_at'
    }
  },
  {
    sequelize,
    modelName: 'CpcAuditLog',
    tableName: 'cpc_audit_logs',
    timestamps: false
  }
);

CpcAuditLog.belongsTo(sequelize.models.CpcDocument, {
    foreignKey: 'documentId',
    targetKey: 'id',
    as: 'document'
});

export { CpcAuditLog };

