const { DataTypes } = require('sequelize');

module.exports = (sequelize) => {
    const HandoverCompletion = sequelize.define('handoverCompletion', {
        id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        creation: { type: DataTypes.DATE, allowNull: false },
        modified: { type: DataTypes.DATE, allowNull: false },
        modified_by: { type: DataTypes.INTEGER, allowNull: false },
        owner: { type: DataTypes.INTEGER, allowNull: false },
        enabled: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
        
        handover_number: { type: DataTypes.STRING(50), allowNull: false, unique: true },
        request_id: { type: DataTypes.INTEGER, allowNull: false },
        app_id: { type: DataTypes.INTEGER, allowNull: true },
        system_version: { type: DataTypes.STRING(50), allowNull: true },
        handover_date: { type: DataTypes.DATEONLY, allowNull: false },
        location: { type: DataTypes.STRING(255), allowNull: true },
        receiver_id: { type: DataTypes.INTEGER, allowNull: false },
        programmer_id: { type: DataTypes.INTEGER, allowNull: false },
        it_manager_id: { type: DataTypes.INTEGER, allowNull: false },
        status: { type: DataTypes.STRING(20), allowNull: false, defaultValue: 'Draft' },

        doc_no: { type: DataTypes.STRING(50), allowNull: true },
        issue_date: { type: DataTypes.DATEONLY, allowNull: true },
        rev_no: { type: DataTypes.STRING(10), allowNull: true, defaultValue: '0' },
        rev_date: { type: DataTypes.DATEONLY, allowNull: true },
    }, {
        tableName: 'handovercompletions',
        freezeTableName: true
    });

    HandoverCompletion.associate = (models) => {
        HandoverCompletion.belongsTo(models.HandoverRequest, { foreignKey: "request_id", as: "request" });
        HandoverCompletion.belongsTo(models.App, { foreignKey: "app_id", as: "app" });
        HandoverCompletion.belongsTo(models.Employee, { foreignKey: "receiver_id", as: "receiver" });
        HandoverCompletion.belongsTo(models.Employee, { foreignKey: "programmer_id", as: "programmer" });
        HandoverCompletion.belongsTo(models.Employee, { foreignKey: "it_manager_id", as: "it_manager" });
        HandoverCompletion.belongsTo(models.User, { foreignKey: "modified_by", as: "modifier" });
        
        HandoverCompletion.hasMany(models.HandoverFeature, { foreignKey: "handover_id", as: "features" });
        HandoverCompletion.hasMany(models.HandoverTest, { foreignKey: "handover_id", as: "tests" });
    };

    return HandoverCompletion;
};
