const { Product, User } = 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 {
        product_name,
        price,
        product_descp
    } = req.body;

    const { user_id, branch_id } = req.auth;

    const paramNames = ["Product Name", "Product Price"];
    const { hasNull, missingParams } = isNull([product_name, price]);
    if (hasNull || price <= 0) {
        const missingParamNames = missingParams.map(index => paramNames[index]);
        if (price <= 0) {
            return sendAppError(extras, `Price should be greater than zero`, STATUS_CODE.BAD_REQUEST);
        }
        return sendAppError(extras, `${missingParamNames.join(', ')} ${missingParamNames.length > 1 ? 'are' : 'is'} required`, STATUS_CODE.BAD_REQUEST);
    }
    try {
        const findProduct = await Product.findOne({
            where: {
                [Op.or]: [
                    { product_name }
                ],
            },
        });

        if (findProduct) {
            if (findProduct.product_name === product_name) {
                return sendAppError(extras, "Product Name already exists", STATUS_CODE.BAD_REQUEST);
            }
        }

        const product = await Product.create({
            branch_id,
            product_name,
            price,
            product_descp,
            created_by: user_id
        }, { transaction: extras.transaction });

        await extras.transaction.commit();
        const productDetails = await getDetails(product.product_id);
        return res.sendRes(productDetails, { message: 'Product created successfully', status: STATUS_CODE.OK });
    } catch (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, order_by } = req.query;
    const { branch_id } = req.auth;
    let findObj = findObject(search, branch_id, active_status);
    try {
        const products = await Product.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', order_by == 1 ? 'ASC' : 'DESC']],
            ...req.paginate,
        });

        return res.sendRes(products, {
            message: 'Products loaded successfully',
            ...req.meta,
            total: await Product.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] = [
            { product_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 { product_id } = req.params;

    try {
        const product = await Product.findOne({
            where: { product_id }
        });

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

        return res.sendRes(product, { message: 'Product 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 { product_id } = req.params;
    const { user_id } = req.auth;
    const { product_name, price, product_descp, changeStatus } = req.body;

    try {
        const product = await Product.findOne({
            where: { product_id },
        });

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

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

            await extras.transaction.commit();
            const productDetails = await getDetails(product.product_id);
            return res.sendRes(productDetails, { message: 'Product status updated successfully', status: STATUS_CODE.OK });
        }

        if (product_name) {
            const findProduct = await Product.findOne({
                where: {
                    product_name,
                    branch_id,
                    product_id: { [Op.ne]: product_id }
                },
                paranoid: false,
            });

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

        await product.update({
            product_name,
            price,
            product_descp,
            updated_by: user_id,
        }, { transaction: extras.transaction });

        await extras.transaction.commit();
        const productDetails = await getDetails(product.product_id);
        return res.sendRes(productDetails, { message: 'Product 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 { product_id } = req.params;

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

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

        await product.destroy({ transaction: extras.transaction });
        await extras.transaction.commit();
        return res.sendRes(null, { message: 'Product 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 productsData = [];
    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, rowProductName, rowProductPrice, rowProductDesc } = row;
                            if (!rowProductName || !rowProductPrice) {
                                errors.push(`Product Name and Product Price are required for row: ${rowRefId}`);
                            } else {
                                try {
                                    const existingProduct = await Product.findOne({ where: { product_name: rowProductName } });

                                    if (!existingProduct) {
                                        productsData.push({
                                            tbl_ref_id: rowRefId,
                                            branch_id: branch_id,
                                            product_name: rowProductName,
                                            price: rowProductPrice,
                                            product_descp: rowProductDesc,
                                            created_by: user_id
                                        });
                                    }
                                } catch (dbError) {
                                    errors.push(`Database error in row: ${rowRefId}`);
                                }
                            }
                        })()
                    );
                })
                .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 products = await Product.bulkCreate(productsData, { transaction: extras.transaction });
            await extras.transaction.commit();
            return res.sendRes(products, { message: 'Products created successfully', status: STATUS_CODE.OK });
        } catch (error) {
            await extras.transaction.rollback();
            return sendAppError(extras, 'Failed to create Products', 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 Product.findOne({
        where: { product_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
};
