const { Landmark, 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 {
        area_id,
        landmark_name,
        landmark_descp
    } = req.body;

    const { user_id, branch_id } = req.auth;

    const paramNames = ["Area Name", "Landmark Name"];
    const { hasNull, missingParams } = isNull([area_id, landmark_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 findLandmark = await Landmark.findOne({
            where: {
                [Op.or]: [
                    { landmark_name }
                ],
            },
        });

        if (findLandmark) {
            if (findLandmark.landmark_name === landmark_name) {
                return sendAppError(extras, "Landmark Name already exists", STATUS_CODE.BAD_REQUEST);
            }
        }

        const landmark = await Landmark.create({
            branch_id,
            area_id,
            landmark_name,
            landmark_descp,
            created_by: user_id
        }, { transaction: extras.transaction });

        await extras.transaction.commit();
        const landmarkDetails = await getDetails(landmark.landmark_id);
        return res.sendRes(landmarkDetails, { message: 'Landmark 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, area_id, order_by } = req.query;
    const { branch_id } = req.auth;
    let findObj = findObject(search, branch_id, active_status, area_id);
    try {
        const landmarks = await Landmark.findAll({
            where: findObj,
            include: [
                {
                    model: Area,
                    as: 'area',
                    attributes: ['area_id', 'area_name'],
                },
                {
                    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(landmarks, {
            message: 'Landmarks loaded successfully',
            ...req.meta,
            total: await Landmark.count({
                where: findObj,
                include: [
                    {
                        model: Area,
                        as: 'area',
                        attributes: [],
                    },
                ],
            }),
            status: STATUS_CODE.OK,
        });

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

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

    if (search) {
        findObj[Op.or] = [
            { landmark_name: { [Op.substring]: search } },
            { landmark_descp: { [Op.substring]: search } },
            { '$area.area_name$': { [Op.substring]: search } }
        ];
    }

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

    return findObj;
}

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

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

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

        return res.sendRes(landmark, { message: 'Landmark 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 { landmark_id } = req.params;
    const { user_id } = req.auth;
    const { area_id, landmark_name, landmark_descp, changeStatus } = req.body;

    try {
        const landmark = await Landmark.findOne({
            where: { landmark_id },
        });

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

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

            await extras.transaction.commit();
            const landmarkDetails = await getDetails(landmark.landmark_id);
            return res.sendRes(landmarkDetails, { message: 'Landmark status updated successfully', status: STATUS_CODE.OK });
        }

        if (landmark_name) {
            const findLandmark = await Landmark.findOne({
                where: {
                    landmark_name,
                    branch_id,
                    landmark_id: { [Op.ne]: landmark_id },
                },
                paranoid: false,
            });

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

        await landmark.update({
            area_id,
            landmark_name,
            landmark_descp,
            updated_by: user_id,
        }, { transaction: extras.transaction });

        await extras.transaction.commit();
        const landmarkDetails = await getDetails(landmark.landmark_id);
        return res.sendRes(landmarkDetails, { message: 'Landmark 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 { landmark_id } = req.params;

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

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

        await landmark.destroy({ transaction: extras.transaction });
        await extras.transaction.commit();
        return res.sendRes(null, { message: 'Landmark 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 landmarksData = [];
    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, rowLandmarkName, rowLandmarkDesc, rowAreaId } = row;
                            if (!rowLandmarkName) {
                                errors.push('Landmark Name is required');
                            } else {
                                try {
                                    const existingLandmark = await Landmark.findOne({ where: { landmark_name: rowLandmarkName } });
                                    const existingArea = await Area.findOne({ where: { tbl_ref_id: rowAreaId } });

                                    if (!existingLandmark && !existingArea) {
                                        landmarksData.push({
                                            tbl_ref_id: rowRefId,
                                            branch_id: branch_id,
                                            area_id: existingArea.area_id,
                                            landmark_name: rowLandmarkName,
                                            landmark_descp: rowLandmarkDesc,
                                            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 landmarks = await Landmark.bulkCreate(landmarksData, { transaction: extras.transaction });
            await extras.transaction.commit();
            return res.sendRes(landmarks, { message: 'Landmarks created successfully', status: STATUS_CODE.OK });
        } catch (error) {
            await extras.transaction.rollback();
            return sendAppError(extras, 'Failed to create Landmarks', 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 Landmark.findOne({
        where: { landmark_id: id },
        include: [
            {
                model: Area,
                as: 'area',
                attributes: ['area_id', 'area_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
};
