const dbSAPPS = require('../../helpers/db');
require('dotenv').config();
const { Op } = require('sequelize');

module.exports = {
    create,
    getAll,
    filter,
    option,
    optionParent,
    count,
    update,
    enabled,
    delete: _delete
};

async function getAll() {
    try {
        const territories = await dbSAPPS.Territory.findAll({
            order: [['modified', 'DESC']],
            include: {
                model: dbSAPPS.Company,
                as: 'company',
                attributes: ['name']
            }
        });

        return {
            territories,
            success: true,
            message: 'Territories has been loaded!'
        };
    } catch (error) {
        const errorMessage = error.message || 'Failed to load territories!';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function filter(params) {
    const filterConditions = {};

    if (params.name) {
        filterConditions.name = {
            [Op.like]: `%${params.name}%`,
        };
    }

    if (params.display_name) {
        filterConditions.display_name = {
            [Op.like]: `%${params.display_name}%`,
        };
    }

    if (params.slug_name) {
        filterConditions.slug_name = {
            [Op.like]: `%${params.slug_name}%`,
        };
    }

    if (params.code) {
        filterConditions.code = {
            [Op.like]: `%${params.code}%`,
        };
    }

    if (params.company_id) {
        filterConditions.company_id = {
            [Op.like]: `%${params.company_id}%`,
        };
    }

    if (params.is_parent) {
        filterConditions.is_parent = {
            [Op.eq]: params.is_parent === "1" ? true : false,
        };
    }

    if (params.enabled) {
        filterConditions.enabled = {
            [Op.eq]: params.enabled === "1" ? true : false,
        };
    }

    try {
        const territories = await dbSAPPS.Territory.findAll({
            where: filterConditions,
            order: [['modified', 'DESC']],
            include: {
                model: dbSAPPS.Company,
                as: 'company',
                attributes: ['name']
            }
        });

        return {
            territories,
            success: true,
            message: 'Territories has been loaded!'
        };
    } catch (error) {
        console.error('Error retrieving territories: ', error);
        const errorMessage = error.message || 'Failed to retrieve territories. Please try again later.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function option() {
    try {
        const territories = await dbSAPPS.Territory.findAll({
            attributes: ['id', 'name', 'display_name', 'slug_name', 'code', 'is_parent', 'description', 'company_id'],
            where: { enabled: true },
            order: [['name', 'ASC']],
            include: {
                model: dbSAPPS.Company,
                as: 'company',
                attributes: ['name']
            }
        });

        return {
            territories,
            success: true,
            message: 'Territories has been loaded!'
        };
    } catch (error) {
        console.error('Error retrieving territories: ', error);
        const errorMessage = error.message || 'Failed to retrieve territories. Please try again later.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function optionParent() {
    try {
        const territories = await dbSAPPS.Territory.findAll({
            attributes: ['id', 'name', 'display_name', 'slug_name', 'code', 'is_parent', 'description'],
            where: {
                enabled: true,
                is_parent: true
            },
            order: [['name', 'ASC']]
        });

        return {
            territories,
            success: true,
            message: "Territories has been loaded!"
        };
    } catch (error) {
        console.error('Error retrieving territories: ', error);
        const errorMessage = error.message || 'Failed to retrieve territories. Please try again later.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function count() {
    try {
        const count = await dbSAPPS.Territory.count({
            where: { enabled: true }
        });

        return {
            count,
            success: true,
            message: "Territories has been loaded!"
        };
    } catch (error) {
        console.error('Error counting territories: ', error);
        return {
            success: false,
            message: 'Failed to retrieve territories count. Please try again later.'
        };
    }
}

async function create(params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        if (!params.name || !params.display_name) return { success: false, message: 'Name and display name are required!' };

        const existingName = await dbSAPPS.Territory.findOne({ where: { name: params.name, company_id: params.company_id }, transaction });
        if (existingName) return { success: false, message: `Name "${params.name}" is already taken.` };

        const existingDisplayName = await dbSAPPS.Territory.findOne({ where: { display_name: params.display_name, company_id: params.company_id }, transaction });
        if (existingDisplayName) return { success: false, message: `display name "${params.display_name}" is already taken.` };

        await dbSAPPS.Territory.create(params, { transaction });
        await transaction.commit();
        return {
            success: true,
            message: 'Territory has been created!',
        };
    } catch (error) {
        await transaction.rollback();
        const errorMessage = error.message || 'An error occurred during creating territory.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function update(id, params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        const territory = await dbSAPPS.Territory.findByPk(id, { transaction });
        if (!territory) return {
            success: false,
            message: 'Territory not found!'
        };

        if (params.name && params.name !== territory.name) {
            const existingName = await dbSAPPS.Territory.findOne({ where: { name: params.name, company_id: params.company_id }, transaction });
            if (existingName) {
                if (existingName.id != params.id) {
                    return {
                        success: false,
                        message: `Name "${params.name}" is already taken. Try again!`
                    };
                }
            }
        }

        if (params.display_name && params.display_name !== territory.display_name) {
            const existingDisplayName = await dbSAPPS.Territory.findOne({ where: { display_name: params.display_name, company_id: params.company_id }, transaction });
            if (existingDisplayName) {
                if (existingDisplayName.id != params.id) {
                    return {
                        success: false,
                        message: `Display name "${params.display_name}" is already taken. Try again!`
                    };
                }
            }
        }

        await territory.update(params, { transaction });
        await transaction.commit();
        return {
            success: true,
            message: 'Territory has been updated!'
        };
    } catch (error) {
        await transaction.rollback();
        const errorMessage = error.message || 'Failed to update territory.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function enabled(id, params) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        const territory = await dbSAPPS.Territory.findByPk(id, { transaction });
        if (!territory) return {
            success: false,
            message: 'Territory not found!'
        };

        const updateData = {};
        updateData.enabled = params.enabled;
        if (params.modified_by) updateData.modified_by = params.modified_by;
        if (params.modified) updateData.modified = params.modified;

        await territory.update(updateData, { transaction });
        await transaction.commit();
        return {
            success: true,
            message: 'Territory has been updated!'
        };
    } catch (error) {
        await transaction.rollback();
        const errorMessage = error.message || 'Failed to update territory.';
        return {
            success: false,
            message: errorMessage
        };
    }
}

async function _delete(id) {
    const transaction = await dbSAPPS.sequelize.transaction();
    try {
        const territory = await dbSAPPS.Territory.findByPk(id, { transaction });
        if (!territory) return {
            success: false,
            message: 'Territory not found!'
        };

        await territory.destroy({ transaction });
        await transaction.commit();
        return {
            success: true,
            message: 'Territory has been deleted!'
        };
    } catch (error) {
        await transaction.rollback();
        const errorMessage = error.message || 'Failed to delete territory.';
        return {
            success: false,
            message: errorMessage
        };
    }
}
