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

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

async function getAll() {
    try {
        const ucSettings = await dbSAPPS.UcSetting.findAll();
        return {
            ucSettings,
            success: true,
            message: "UC settings loaded successfully!",
        };
    } catch (error) {
        const errorMessage = error.message || "Failed to load up country settings!";
        return {
            success: false,
            message: errorMessage,
        };
    }
}

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

    if (params.enabled) {
        filterConditions.enabled = {
            [Op.eq]: params.enabled === "1" ? true : false,
        };
    }
    try {
        const ucSettings = await dbSAPPS.UcSetting.findAll({
            where: filterConditions,
            order: [["modified", "DESC"]],
            include: [
                {
                    model: dbSAPPS.DocType,
                    as: "doctype",
                    attributes: ["id", "name", "display_name"],
                },
            ],
        });

        return {
            ucSettings,
            success: true,
            message: "up country settings loaded successfully!",
        };
    } catch (error) {
        console.error("Error retrieving up country settings: ", error);
        const errorMessage =
            error.message || "Failed to retrieve up country settings. Please try again later.";
        return {
            success: false,
            message: errorMessage,
        };
    }
}

async function option() {
    try {
        const ucSettings = await dbSAPPS.UcSetting.findAll({
            attributes: ["id", "doctype_id", "type", "limit"],
            where: { enabled: true },
            order: [["modified", "ASC"]],
            include: [
                {
                    model: dbSAPPS.DocType,
                    as: "doctype",
                    attributes: ["id", "name", "display_name"],
                },
            ],
        });

        return {
            ucSettings,
            success: true,
            message: "up country settings loaded successfully!",
        };
    } catch (error) {
        console.error("Error retrieving up country settings: ", error);
        const errorMessage =
            error.message || "Failed to retrieve up country settings. Please try again later.";
        return {
            success: false,
            message: errorMessage,
        };
    }
}

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

        return {
            count,
            success: true,
            message: "up country settings loaded successfully!",
        };
    } catch (error) {
        console.error("Error counting up country settings: ", error);
        return {
            success: false,
            message: "Failed to retrieve up country settings count. Please try again later.",
        };
    }
}


async function createOrUpdate(params) {
    try {
        const [ucSetting, created] = await dbSAPPS.UcSetting.findOrCreate({
            where: { id: params.id },
            defaults: params,
        });

        if (created) {
            return {
                success: true,
                message: "up country settings data has been successfully added!",
            };
        }

        await ucSetting.update(params);
        return {
            success: true,
            message: "Data up country settings has been saved!",
        };
    } catch (error) {
        const errorMessage =
            error.message || "An error occurred during create or update up country settings processing.";
        return {
            success: false,
            message: errorMessage,
        };
    }
}

async function enabled(id, params) {
    try {
        const ucSetting = await dbSAPPS.UcSetting.findByPk(id);
        if (!ucSetting)
            return {
                success: false,
                message: "up country settings 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 ucSetting.update(updateData);
        return {
            success: true,
            message: "up country settings has been updated!",
        };
    } catch (error) {
        const errorMessage = error.message || "Failed to update up country settings.";
        return {
            success: false,
            message: errorMessage,
        };
    }
}

async function _delete(id) {
    try {
        const ucSetting = await dbSAPPS.UcSetting.findByPk(id);
        if (!ucSetting) return { success: false, message: "up country settings not found!" };

        await ucSetting.destroy();

        return {
            success: true,
            message: "up country settings successfully deleted!",
        };
    } catch (error) {
        const errorMessage = error.message || "Failed to delete up country settings.";
        return {
            success: false,
            message: errorMessage,
        };
    }
}
