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

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

async function getAll() {
    try {
        const workflowSettings = await dbSAPPS.WorkflowSetting.findAll({
            order: [["modified", "DESC"]],
            include: [
                {
                    model: dbSAPPS.DocType,
                    as: "doctype",
                    attributes: ["id", "name", "display_name"],
                },
            ],
        });

        return {
            workflowSettings,
            success: true,
            message: "Workflow settings loaded successfully!",
        };
    } catch (error) {
        const errorMessage = error.message || "Failed to load workflow settings!";
        return {
            success: false,
            message: errorMessage,
        };
    }
}

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

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

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

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

async function option() {
    try {
        const workflowSettings = await dbSAPPS.WorkflowSetting.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 {
            workflowSettings,
            success: true,
            message: "workflow settings loaded successfully!",
        };
    } catch (error) {
        console.error("Error retrieving workflow settings: ", error);
        const errorMessage =
            error.message || "Failed to retrieve workflow settings. Please try again later.";
        return {
            success: false,
            message: errorMessage,
        };
    }
}

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

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

async function create(params) {
    try {
        if (!params.doctype_id)
            return {
                success: false,
                message: "workflow settings doctype_id are required!",
            };

        const existing = await dbSAPPS.WorkflowSetting.findOne({
            where: {
                doctype_id: params.doctype_id,
                type: params.type,
            },
        });

        if (existing)
            return {
                success: false,
                message: `workflow settings doctype_id "${params.doctype_id}" and type "${params.type}" is already taken.`,
            };

        if (!params.enabled) params.enabled = true;
        await dbSAPPS.WorkflowSetting.create(params);

        return {
            success: true,
            message: "workflow settings data has been successfully added!",
        };
    } catch (error) {
        const errorMessage =
            error.message || "An error occurred during create workflow settings processing.";
        return {
            success: false,
            message: errorMessage,
        };
    }
}

async function update(id, params) {
    try {
        const workflowSetting = await dbSAPPS.WorkflowSetting.findByPk(id);
        if (!workflowSetting)
            return {
                success: false,
                message: "workflow settings not found!",
            };

        if (params.doctype_id && params.doctype_id !== workflowSetting.doctype_id) {
            const existing = await dbSAPPS.WorkflowSetting.findOne({
                where: { doctype_id: params.doctype_id },
            });
            if (existing) {
                return {
                    success: false,
                    message: `workfolw settings doctype_id "${params.doctype_id}" is already taken. Try again!`,
                };
            }
        }

        await workflowSetting.update(params);
        return {
            success: true,
            message: "Data workflow settings has been saved!",
        };
    } catch (error) {
        const errorMessage = error.message || "Failed to update workflow settings data.";
        return {
            success: false,
            message: errorMessage,
        };
    }
}

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

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

        await workflowSetting.destroy();

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