const { User, UserRights } = require("../../models");
const { SERVER_ERROR } = require("../../utils/errorMessage");
const { STATUS_CODE } = require("../../utils/utility");
const routeHandler = require("../../utils/routeHandler");
const { isNull } = require("../../utils/validation");
const { sendAppError } = require("../../utils/appError");
const settings = require("../../models/settings");

const create = routeHandler(async (req, res, extras, next) => {
    const {
        user_id,
        master_ins,
        master_upd,
        master_del,
        user_ins,
        user_upd,
        user_del,
        order_ins,
        order_upd,
        order_del,
        collection_ins,
        collection_upd,
        collection_del,
        return_ins,
        return_del,
        expenses_ins,
        expenses_upd,
        expenses_del,
        draft_view,
        draft_del,
        reports_view,
        settings_view,
        settings_upd,
        outstanding_view,
        userright_ins,
        userright_view
    } = req.body;

    const paramNames = ["User Id"];
    const { hasNull, missingParams } = isNull([user_id]);
    if (hasNull) {
        const missingParamNames = missingParams.map(index => paramNames[index]);
        return sendAppError(
            extras,
            `${missingParamNames.join(', ')} ${missingParamNames.length > 1 ? 'are' : 'is'} required`,
            STATUS_CODE.BAD_REQUEST
        );
    }

    const permissions = {
        master_ins,
        master_upd,
        master_del,
        user_ins,
        user_upd,
        user_del,
        order_ins,
        order_upd,
        order_del,
        collection_ins,
        collection_upd,
        collection_del,
        return_ins,
        return_del,
        expenses_ins,
        expenses_upd,
        expenses_del,
        draft_view,
        draft_del,
        reports_view,
        settings_view,
        settings_upd,
        outstanding_view,
        userright_ins,
        userright_view
    };

    try {
        let userRight = await UserRights.findOne({
            where: { user_id },
        });
        let updatedUserRights;
        if (userRight) {
            updatedUserRights = await userRight.update({
                user_rights_permission: JSON.stringify(permissions),
                updated_by: req.auth.user_id
            }, { transaction: extras.transaction });
        } else {
            updatedUserRights = await UserRights.create(
                {
                    user_id,
                    user_rights_permission: JSON.stringify(permissions),
                    created_by: req.auth.user_id
                },
                { transaction: extras.transaction }
            );
        }
        await extras.transaction.commit();
        return res.sendRes(updatedUserRights, { message: 'User Right created successfully', status: STATUS_CODE.OK });
    } catch (error) {
        if (extras.transaction) {
            await extras.transaction.rollback();
        }
        return sendAppError(extras, SERVER_ERROR, STATUS_CODE.INTERNAL_SERVER_ERROR);
    }
});

const getById = routeHandler(async (req, res, extras) => {
    const { user_id } = req.params;

    try {
        const userRight = await UserRights.findOne({
            where: { user_id },
            include: [
                {
                    model: User,
                    as: 'user',
                    attributes: ['user_id', 'fullname'],
                },
            ],
        });

        // if (!userRight) {
        //     return sendAppError(extras, 'User Right not found', STATUS_CODE.NOT_FOUND);
        // }

        return res.sendRes(userRight, { message: 'User Right loaded successfully', status: STATUS_CODE.OK });
    } catch (error) {
        console.error(error);
        if (extras.transaction) {
            await extras.transaction.rollback();
        }
        return sendAppError(extras, error.message, STATUS_CODE.INTERNAL_SERVER_ERROR);
    }
}, false);

module.exports = {
    create,
    getById
};
