const Sequelize = require('sequelize');

module.exports = function (sequelize, DataTypes) {
    const Entity = sequelize.define('Entity', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true,
        },
        name: {
            type: DataTypes.STRING,
            allowNull: false
        },
        state: {
            type: DataTypes.STRING(45),
            allowNull: false,
            default: 'draft',
        },
        contact_person: {
            type: DataTypes.STRING,
        },
        contact_email: {
            type: DataTypes.STRING,
        },
        level: {
            type: DataTypes.STRING,
        },
        country: {
        type: DataTypes.STRING,
        defaultValue: "ES",
        },
    }, {
        tableName: 'entities',
        freezeTableName: true,
        timestamps: true,

        defaultScope: {
            where: {
                state: 'publish'
            },
        },        
    });

    Entity.associate = function (models) {
        Entity.EntityTypes = Entity.belongsToMany(models.EntityType, { 
            through: models.EntityEntitiesTypes,
            foreignKey: 'entityId',
            as: 'types'
        });
        Entity.User = Entity.hasMany(models.User, { foreignKey: 'entityId' });
        Entity.EventsReservations = Entity.hasMany(models.EventReservation, { foreignKey: 'entityId', as: 'reservations' });
    };

    Entity.addScope('withEntityTypes', () => {
        return {
            include: [{
                model: sequelize.models.EntityType,
                as: 'types',
            }]
        }
    });

    Entity.addScope('onlyColleges', () => {
        return {
            include: [{ model: sequelize.models.EntityType, 
                      as: 'types',
                      where: {alias: 'college'},
                      attributes: [],
            }]
        }
    });

    Entity.addScope('onlyPartners', () => {
        return {
            include: [{
                model: sequelize.models.EntityType,
                as: 'types',
                where: { alias: 'partner' },
                attributes: [],                
            }]
        }
    });

    return Entity;
};