import { Model, DataTypes, Sequelize } from 'sequelize';

export interface ConstitutionalAuditAttributes {
    id: string;
    userId: string | null;
    constitutionalChangeId: string;
    action: string;
    details: any | null;
    remarks: string | null;
}

export interface ConstitutionalAuditInstance extends Model<ConstitutionalAuditAttributes>, ConstitutionalAuditAttributes { }

export default (sequelize: Sequelize) => {
    const ConstitutionalAudit = sequelize.define<ConstitutionalAuditInstance>('ConstitutionalAudit', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        userId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        constitutionalChangeId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'constitutional_changes',
                key: 'id'
            }
        },
        action: {
            type: DataTypes.STRING,
            allowNull: false
        },
        details: {
            type: DataTypes.JSON,
            allowNull: true
        },
        remarks: {
            type: DataTypes.TEXT,
            allowNull: true
        }
    }, {
        tableName: 'constitutional_audit_logs',
        timestamps: true,
        indexes: [
            { fields: ['constitutionalChangeId'] },
            { fields: ['userId'] },
            { fields: ['action'] }
        ]
    });

    (ConstitutionalAudit as any).associate = (models: any) => {
        ConstitutionalAudit.belongsTo(models.User, { foreignKey: 'userId', as: 'user' });
        ConstitutionalAudit.belongsTo(models.ConstitutionalChange, { foreignKey: 'constitutionalChangeId', as: 'constitutionalChange' });
    };

    return ConstitutionalAudit;
};
