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

export interface ApplicationStatusHistoryAttributes {
    id: string;
    applicationId: string;
    previousStatus: string | null;
    newStatus: string;
    changedBy: string | null;
    changeReason: string | null;
}

export interface ApplicationStatusHistoryInstance extends Model<ApplicationStatusHistoryAttributes>, ApplicationStatusHistoryAttributes { }

export default (sequelize: Sequelize) => {
    const ApplicationStatusHistory = sequelize.define<ApplicationStatusHistoryInstance>('ApplicationStatusHistory', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        applicationId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'applications',
                key: 'id'
            }
        },
        previousStatus: {
            type: DataTypes.STRING,
            allowNull: true
        },
        newStatus: {
            type: DataTypes.STRING,
            allowNull: false
        },
        changedBy: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        changeReason: {
            type: DataTypes.TEXT,
            allowNull: true
        }
    }, {
        tableName: 'application_status_history',
        timestamps: true,
        updatedAt: false
    });

    (ApplicationStatusHistory as any).associate = (models: any) => {
        ApplicationStatusHistory.belongsTo(models.Application, { foreignKey: 'applicationId', as: 'application' });
        ApplicationStatusHistory.belongsTo(models.User, { foreignKey: 'changedBy', as: 'changer' });
    };

    return ApplicationStatusHistory;
};
