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

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

            doc_no: { type: DataTypes.STRING, allowNull: true },
            doc_date: { type: DataTypes.DATE, allowNull: false },
            from_date: { type: DataTypes.DATEONLY, allowNull: true },
            to_date: { type: DataTypes.DATEONLY, allowNull: true },
            note: { type: DataTypes.TEXT, allowNull: true },

            // fk
            distributor_id: {
                type: DataTypes.INTEGER,
                allowNull: true,
                references: {
                    model: "distributors",
                    key: "id",
                },
            },
            distributorbranch_id: {
                type: DataTypes.INTEGER,
                allowNull: true,
                references: {
                    model: "distributorbranchs",
                    key: "id",
                },
            },
            outlet_id: {
                type: DataTypes.INTEGER,
                allowNull: true,
                references: {
                    model: "outlets",
                    key: "id",
                },
            },
            territory_id: {
                type: DataTypes.INTEGER,
                allowNull: true,
                references: {
                    model: "territories",
                    key: "id",
                },
            },
            company_id: {
                type: DataTypes.INTEGER,
                allowNull: true,
                references: {
                    model: "companies",
                    key: "id",
                },
            },
        },
        {
            tableName: "udps",
            freezeTableName: true,
        }
    );

    Udp.associate = (models) => {
        Udp.belongsTo(models.Company, { foreignKey: "company_id", as: "company" });
        Udp.belongsTo(models.Distributor, { foreignKey: "distributor_id", as: "distributor" });
        Udp.belongsTo(models.DistributorBranch, { foreignKey: "distributorbranch_id", as: "distributorbranch" });
        Udp.belongsTo(models.Outlet, { foreignKey: "outlet_id", as: "outlet" });
        Udp.belongsTo(models.Territory, { foreignKey: "territory_id", as: "territory" });
        Udp.hasMany(models.UdpProduct, { foreignKey: "udp_id", as: "udpproducts" });
    };

    return Udp;
};
