const { Designation, User, Area } = require("../../models");
const { NO_FILE, 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 { Op, fn, col, literal } = require("sequelize");
const fastcsv = require('fast-csv');
const path = require('path');
const fs = require('fs');

const create = routeHandler(async (req, res, extras, next) => {
    const {
        designation_name,
        designation_descp
    } = req.body;

    const { user_id, branch_id } = req.auth;

    const paramNames = ["Designation Name"];
    const { hasNull, missingParams } = isNull([designation_name]);
    if (hasNull) {
        const missingParamNames = missingParams.map(index => paramNames[index]);
        return sendAppError(extras, `${missingParamNames.join(', ')} ${missingParamNames.length > 1 ? 'are' : 'is'} required`, STATUS_CODE.BAD_REQUEST);
    }
    try {
        const findDesignation = await Designation.findOne({
            where: {
                [Op.or]: [
                    { designation_name }
                ],
            },
        });

        if (findDesignation) {
            if (findDesignation.designation_name === designation_name) {
                return sendAppError(extras, "Designation Name already exists", STATUS_CODE.BAD_REQUEST);
            }
        }

        const designation = await Designation.create({
            branch_id,
            designation_name,
            designation_descp,
            created_by: user_id
        }, { transaction: extras.transaction });

        await extras.transaction.commit();
        const designationDetails = await getDetails(designation.designation_id);
        return res.sendRes(designationDetails, { message: 'Designation created successfully', status: STATUS_CODE.OK });
    } catch (error) {
        console.log("error")
        console.log(error)
        await extras.transaction.rollback();
        return sendAppError(extras, SERVER_ERROR, STATUS_CODE.INTERNAL_SERVER_ERROR);
    }
});

const getAll = routeHandler(async (req, res, extras) => {
    const { search, active_status } = req.query;
    const { branch_id } = req.auth;
    let findObj = findObject(search, branch_id, active_status);
    try {
        const designations = await Designation.findAll({
            where: findObj,
            include: [
                {
                    model: User,
                    as: 'user_created',
                    attributes: ['user_id', 'fullname'],
                },
                {
                    model: User,
                    as: 'user_updated',
                    attributes: ['user_id', 'fullname'],
                },
            ],
            order: [['created_at', 'DESC'],],
            ...req.paginate,
        });

        return res.sendRes(designations, {
            message: 'Designations loaded successfully',
            ...req.meta,
            total: await Designation.count({
                where: findObj,
            }),
            status: STATUS_CODE.OK,
        });

    } catch (error) {
        await extras.transaction.rollback();
        return sendAppError(extras, error.message, STATUS_CODE.INTERNAL_SERVER_ERROR);
    }
}, false);

function findObject(search, branch_id, active_status) {
    let findObj = {};

    if (search) {
        findObj[Op.or] = [
            { designation_name: { [Op.substring]: search } },
        ];
    }

    if (branch_id && branch_id != 'undefined') findObj.branch_id = branch_id;
    if (active_status && active_status != 'undefined') findObj.active_status = active_status;

    return findObj;
}

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

    try {
        const designation = await Designation.findOne({
            where: { designation_id }
        });

        if (!designation) {
            return sendAppError(extras, 'Designation not found', STATUS_CODE.NOT_FOUND);
        }

        return res.sendRes(designation, { message: 'Designation loaded successfully', status: STATUS_CODE.OK });
    } catch (error) {
        await extras.transaction.rollback();
        return sendAppError(extras, error.message, STATUS_CODE.INTERNAL_SERVER_ERROR);
    }
}, false);

const updateById = routeHandler(async (req, res, extras) => {
    const { designation_id } = req.params;
    const { user_id } = req.auth;
    const { area_id, designation_name, designation_descp, changeStatus } = req.body;

    try {
        const designation = await Designation.findOne({
            where: { designation_id },
        });

        if (!designation) {
            return sendAppError(extras, 'Designation not found', STATUS_CODE.NOT_FOUND);
        }

        if (changeStatus) {
            const newStatus = designation.active_status === true ? false : true;
            await designation.update({
                active_status: newStatus,
                updated_by: user_id,
            }, { transaction: extras.transaction });

            await extras.transaction.commit();
            const designationDetails = await getDetails(designation.designation_id);
            return res.sendRes(designationDetails, { message: 'Designation status updated successfully', status: STATUS_CODE.OK });
        }

        if (designation_name) {
            const findDesignation = await Designation.findOne({
                where: {
                    designation_name,
                    branch_id,
                    designation_id: { [Op.ne]: designation_id },
                },
                paranoid: false,
            });

            if (findDesignation) {
                return sendAppError(extras, "Designation Name already exists", STATUS_CODE.BAD_REQUEST);
            }
        }

        await designation.update({
            area_id,
            designation_name,
            designation_descp,
            updated_by: user_id,
        }, { transaction: extras.transaction });

        await extras.transaction.commit();
        const designationDetails = await getDetails(designation.designation_id);
        return res.sendRes(designationDetails, { message: 'Designation details updated successfully', status: STATUS_CODE.OK });

    } catch (error) {
        await extras.transaction.rollback();
        return sendAppError(extras, error.message, STATUS_CODE.INTERNAL_SERVER_ERROR);
    }
});

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

    try {
        const designation = await Designation.findOne({ where: { designation_id } });
        if (!designation) {
            return sendAppError(extras, 'Designation not found', STATUS_CODE.NOT_FOUND);
        }

        await designation.update({
            deleted_by: req.auth.user_id,
        }, { transaction: extras.transaction });

        await designation.destroy({ transaction: extras.transaction });
        await extras.transaction.commit();
        return res.sendRes(null, { message: 'Designation details deleted successfully', status: STATUS_CODE.OK });
    } catch (error) {
        await extras.transaction.rollback();
        return sendAppError(extras, error.message, STATUS_CODE.INTERNAL_SERVER_ERROR);
    }
});

const bulkUpload = routeHandler(async (req, res, extras) => {
    const file = req.file;
    const { user_id, branch_id } = req.auth;

    if (!file) {
        return sendAppError(extras, NO_FILE, STATUS_CODE.BAD_REQUEST);
    }

    const filePath = path.join(__dirname, '../../uploads', file.filename || `${Date.now()}_${file.originalname}`);
    if (file.buffer) {
        fs.writeFileSync(filePath, file.buffer);
    }
    const designationData = [];
    const errors = [];
    const stream = fs.createReadStream(filePath);
    try {
        const processingPromises = [];

        await new Promise((resolve, reject) => {
            fastcsv.parseStream(stream, { headers: true })
                .on('data', (row) => {
                    processingPromises.push(
                        (async () => {
                            const { rowRefId, rowDesignationName, rowDesignationDesc } = row;
                            if (!rowDesignationName) {
                                errors.push('Designation Name is required');
                            } else {
                                try {
                                    const existingDesignation = await Designation.findOne({ where: { designation_name: rowDesignationName } });

                                    if (!existingDesignation) {
                                        designationData.push({
                                            tbl_ref_id: rowRefId,
                                            branch_id: branch_id,
                                            designation_name: rowDesignationName,
                                            designation_descp: rowDesignationDesc,
                                            created_by: user_id
                                        });
                                    }
                                } catch (dbError) {
                                    reject(dbError);
                                }
                            }
                        })()
                    );
                })
                .on('end', async () => {
                    try {
                        await Promise.all(processingPromises);
                        resolve();
                    } catch (err) {
                        reject(err);
                    }
                })
                .on('error', (error) => reject(error));
        });
        if (errors.length > 0) {
            return sendAppError(extras, errors.join(', '), STATUS_CODE.BAD_REQUEST);
        }

        await extras.transaction.begin();
        try {
            const designation = await Designation.bulkCreate(designationData, { transaction: extras.transaction });
            await extras.transaction.commit();
            return res.sendRes(designation, { message: 'Designation created successfully', status: STATUS_CODE.OK });
        } catch (error) {
            await extras.transaction.rollback();
            return sendAppError(extras, 'Failed to create Designation', STATUS_CODE.INTERNAL_SERVER_ERROR);
        }
    } catch (error) {
        return sendAppError(extras, 'Error processing file', STATUS_CODE.INTERNAL_SERVER_ERROR);
    } finally {
        fs.unlinkSync(filePath);
    }
});

async function getDetails(id) {
    return await Designation.findOne({
        where: { designation_id: id },
        include: [
            {
                model: User,
                as: 'user_created',
                attributes: ['user_id', 'fullname'],
            },
            {
                model: User,
                as: 'user_updated',
                attributes: ['user_id', 'fullname'],
            },
        ],
    });
}

module.exports = {
    create,
    getAll,
    getById,
    updateById,
    deleteById,
    bulkUpload
};
