const { Customer, User, Area, Landmark } = 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 {
        area_id,
        landmark_id,
        customer_name,
        mobile_number,
        customer_descp
    } = req.body;

    const { user_id, branch_id } = req.auth;

    const paramNames = ["Area Name", "Landmark Name", "Customer Name"];
    const { hasNull, missingParams } = isNull([area_id, landmark_id, customer_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);
    }
    if (mobile_number && mobile_number.length !== 10) {
        return sendAppError(extras, "Please valid mobile number", STATUS_CODE.BAD_REQUEST);
    }
    try {
        const customer = await Customer.create({
            branch_id,
            area_id,
            landmark_id,
            customer_name,
            mobile_number,
            customer_descp,
            created_by: user_id
        }, { transaction: extras.transaction });

        await extras.transaction.commit();
        const customerDetails = await getDetails(customer.customer_id);
        return res.sendRes(customerDetails, { message: 'Customer 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 } = req.query;
    const { branch_id } = req.auth;
    let findObj = findObject(search, branch_id, active_status);
    try {
        const customers = await Customer.findAll({
            where: findObj,
            attributes: ['customer_id', 'branch_id', 'area_id', 'landmark_id', 'customer_name', 'mobile_number', 'customer_descp', 'active_status', 'created_at', 'updated_at', 'deleted_at', 'created_by', 'updated_by', 'deleted_by', [fn('CONCAT', col('customer_name'), '-', col('mobile_number')), 'customerName_mobileNumber']],
            include: [
                {
                    model: Area,
                    as: 'area',
                    attributes: ['area_id', 'area_name'],
                },
                {
                    model: Landmark,
                    as: 'landmark',
                    attributes: ['landmark_id', 'landmark_name'],
                },
                {
                    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(customers, {
            message: 'Customers loaded successfully',
            ...req.meta,
            total: await Customer.count({
                where: findObj,
                include: [
                    {
                        model: Area,
                        as: 'area',
                        attributes: [],
                    },
                    {
                        model: Landmark,
                        as: 'landmark',
                        attributes: [],
                    },
                ],
            }),
            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] = [
            { customer_name: { [Op.substring]: search } },
            { mobile_number: { [Op.substring]: search } },
            { '$area.area_name$': { [Op.substring]: search } },
            { '$landmark.landmark_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 { customer_id } = req.params;

    try {
        const customer = await Customer.findOne({
            where: { customer_id },
            include: [
                {
                    model: Area,
                    as: 'area',
                    attributes: ['area_id', 'area_name'],
                }
            ],
        });

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

        return res.sendRes(customer, { message: 'Customer 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 { customer_id } = req.params;
    const { user_id } = req.auth;
    const { area_id, landmark_id, customer_name, mobile_number, customer_descp, changeStatus } = req.body;

    try {
        const customer = await Customer.findOne({
            where: { customer_id },
        });

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

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

            await extras.transaction.commit();
            const customerDetails = await getDetails(customer.customer_id);
            return res.sendRes(customerDetails, { message: 'Customer status updated successfully', status: STATUS_CODE.OK });
        }

       /* if (customer_name) {
            const findCustomer = await Customer.findOne({
                where: {
                    customer_name,branch_id
                },
                paranoid: false,
            });

            if (findCustomer) {
                return sendAppError(extras, "Customer Name already exists", STATUS_CODE.BAD_REQUEST);
            }
        } */

        await customer.update({
            area_id,
            landmark_id,
            customer_name,
            mobile_number,
            customer_descp,
            updated_by: user_id,
        }, { transaction: extras.transaction });

        await extras.transaction.commit();
        const customerDetails = await getDetails(customer.customer_id);
        return res.sendRes(customerDetails, { message: 'Customer 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 { customer_id } = req.params;

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

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

        await customer.destroy({ transaction: extras.transaction });
        await extras.transaction.commit();
        return res.sendRes(null, { message: 'customer 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 customersData = [];
    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, rowCustomerName, rowCustomerNum, rowCustomerDesc, rowAreaId, rowLandMarkId } = row;

                            if (!rowCustomerName || !rowAreaId || !rowLandMarkId) {
                                errors.push(`Customer Name, Area ID, and Landmark ID are required for row: ${rowRefId}`);
                            } else {
                                try {
                                    const existingCustomer = await Customer.findOne({ where: { mobile_number: rowCustomerNum } });
                                    const existingArea = await Area.findOne({ where: { tbl_ref_id: rowAreaId } });
                                    const existingLandmark = await Landmark.findOne({ where: { tbl_ref_id: rowLandMarkId } });

                                    if (!existingCustomer && existingArea && existingLandmark) {
                                        customersData.push({
                                            tbl_ref_id: rowRefId,
                                            branch_id: branch_id,
                                            area_id: existingArea.area_id,
                                            landmark_id: existingLandmark.landmark_id,
                                            customer_name: rowCustomerName,
                                            mobile_number: rowCustomerNum,
                                            customer_descp: rowCustomerDesc,
                                            created_by: user_id
                                        });
                                    } else if (!existingArea || !existingLandmark) {
                                        errors.push(`Area or Landmark does not exist for row: ${rowRefId}`);
                                    }
                                } 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);
        }

        const BATCH_SIZE = 1000;
        await extras.transaction.begin();
        try {
            for (let i = 0; i < customersData.length; i += BATCH_SIZE) {
                const batch = customersData.slice(i, i + BATCH_SIZE);
                await Customer.bulkCreate(batch, { transaction: extras.transaction });
            }
            await extras.transaction.commit();
            return res.sendRes(null, { message: 'Customers created successfully', status: STATUS_CODE.OK });
        } catch (error) {
            await extras.transaction.rollback();
            return sendAppError(extras, 'Failed to create customers', 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 Customer.findOne({
        where: { customer_id: id },
        include: [
            {
                model: Area,
                as: 'area',
                attributes: ['area_id', 'area_name'],
            },
            {
                model: Landmark,
                as: 'landmark',
                attributes: ['landmark_id', 'landmark_name'],
            },
            {
                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
};
