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

module.exports = (sequelize) => {
    const Team = sequelize.define(
        "team",
        {
            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 },

            name: { type: DataTypes.STRING(100), allowNull: false },
            display_name: { type: DataTypes.STRING(150), allowNull: false },
            description: { type: DataTypes.TEXT, allowNull: true },

            // fk
            company_id: { type: DataTypes.INTEGER, allowNull: true },

            // sappsv1 or erpnext or others
            idx: { type: DataTypes.STRING, allowNull: true },
            ids: { type: DataTypes.INTEGER, allowNull: true },
            import_from: { type: DataTypes.STRING(100), allowNull: true },
        },
        {
            tableName: "teams",
            freezeTableName: true,
        },
    );

    /**
     * Associates the Team model with other models.
     */
    Team.associate = (models) => {
        /**
         * Associates the Team model with the Company model.
         */
        Team.belongsTo(models.Company, {
            foreignKey: "company_id",
            as: "company",
        });

        /**
         * Associates the Team model with the Employee model.
         */
        Team.hasMany(models.Employee, {
            foreignKey: "team_id",
            as: "employees",
        });

        Team.belongsTo(models.User, { foreignKey: "modified_by", as: "modifier" });
    };

    return Team;
};
