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

export interface StageApprovalActionAttributes {
    id: string;
    applicationId: string;
    interviewId: string | null;
    stageCode: string;
    actorUserId: string;
    actorRole: string;
    decision: 'Approved' | 'Rejected' | 'Hold';
    remarks: string | null;
}

export interface StageApprovalActionInstance extends Model<StageApprovalActionAttributes>, StageApprovalActionAttributes { }

export default (sequelize: Sequelize) => {
    const StageApprovalAction = sequelize.define<StageApprovalActionInstance>('StageApprovalAction', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        applicationId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'applications',
                key: 'id'
            }
        },
        interviewId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'interviews',
                key: 'id'
            }
        },
        stageCode: {
            type: DataTypes.STRING,
            allowNull: false
        },
        actorUserId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        actorRole: {
            type: DataTypes.STRING,
            allowNull: false
        },
        decision: {
            type: DataTypes.ENUM('Approved', 'Rejected', 'Hold'),
            allowNull: false
        },
        remarks: {
            type: DataTypes.TEXT,
            allowNull: true
        }
    }, {
        tableName: 'stage_approval_actions',
        timestamps: true,
        indexes: [
            { fields: ['applicationId'] },
            { fields: ['interviewId'] },
            { fields: ['stageCode'] },
            { fields: ['actorUserId'] },
            { fields: ['interviewId', 'stageCode', 'actorUserId'], unique: true }
        ]
    });

    (StageApprovalAction as any).associate = (models: any) => {
        StageApprovalAction.belongsTo(models.Application, { foreignKey: 'applicationId', as: 'application' });
        StageApprovalAction.belongsTo(models.Interview, { foreignKey: 'interviewId', as: 'interview' });
        StageApprovalAction.belongsTo(models.User, { foreignKey: 'actorUserId', as: 'actor' });
    };

    return StageApprovalAction;
};
