const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/db.js');
const GroupModules = require('./group_modules.js');
const { sanitizeSort, sanitizePagination } = require('./querySafety.js');

class Group extends Model {

    static associate(models) {

        Group.belongsToMany(models.User, {
            through: "user_groups"
        });

        Group.belongsToMany(models.Module, {
            through: GroupModules,
            foreignKey: "groupId",
            otherKey: "moduleId"
        });
    }

    async createGroup(data) {
        try {
            const group = await Group.create(data)
            console.log(group.toJSON());
            return group.toJSON();
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }
    
    async readGroup(ordCol, ordDir, offsetVal, limitVal) {
        try {
            const [safeOrderCol, safeOrderDir] = sanitizeSort(ordCol, ordDir, [
                'id', 'name', 'description', 'status', 'createdAt', 'updatedAt'
            ]);
            const { safeOffset, safeLimit } = sanitizePagination(offsetVal, limitVal);
            const group = await Group.findAll(
                {
                    order: [[safeOrderCol, safeOrderDir]],
                    offset: safeOffset,
                    limit: safeLimit
                }
            );
            console.log(group.map(g => g.toJSON()));
            return group.map(g => g.toJSON());
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }

    async readGroupRow(data) {
        try {
            const group = await Group.findAll(
                {
                    where: {
                        id: data.id
                    }
                }
            )
            console.log(group.map(g => g.toJSON()));
            return group.map(g => g.toJSON());
        }
        catch (err) {
            console.log(err);
            return err;
        }
    } 

    async updateGroup(data) {
        try {
            const result = await Group.update(data.data, {where: {id: data.id}});
            console.log(`Group with ${data.id} updated`, result[0]);
            return result[0];
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }

    async deleteGroup(data) {
        try {
            const result = await Group.destroy(
                {
                    where: {id: data.id}
                }
            );

            if (result) {
                console.log(`Group ${data.id} deleted`);
                return `Group ${data.id} deleted`;
            }
            else {
                console.log(`Group ${data.id} not found`);
                return `Group ${data.id} not found`;
            }
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }

    async countGroup() {
        try {
            const count = await Group.count();
            console.log(count);
            return count;
        }
        catch (err) {
            console.log(err);
            return err;
        }
    }
}

Group.init(
    {
        name: {
            type: DataTypes.STRING(50),
            allowNull: false
        },
        description: {
            type: DataTypes.STRING(250),
            allowNull: false
        },
        status: {
            type: DataTypes.STRING(25),
            allowNull: false
        }
    },
    {
        sequelize,
        modelName: "Group",
        tableName: "groups"
    }
)

module.exports = Group;