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

const PERMIT_EASE_DOCTYPE_ID = 70;

module.exports = {
	getAll,
};

/**
 * Get Permit Eases that need approval for dashboard Workflow Approval card.
 * Uses same approver logic as Workflows Inbox: workflow status "Need Approval", doctype 70,
 * and WorkflowApprover matches designation_id/territory_id (or read_all_data).
 * Optionally filter by employeesId to align with Leave Application / Attendance Request card.
 */
async function getAll(params) {
	try {
		const filterConditionsApprover = {};
		const filterConditionsApproverOr = [];

		if (params.designation_id) {
			filterConditionsApproverOr.push({
				designation_id: {
					[Op.eq]: parseInt(params.designation_id, 10),
				},
			});
		}

		if (params.territory_id) {
			filterConditionsApproverOr.push({
				territory_id: {
					[Op.eq]: parseInt(params.territory_id, 10),
				},
			});
		}

		if (filterConditionsApproverOr.length > 0) {
			filterConditionsApprover[Op.or] = filterConditionsApproverOr;
		}

		const workflowApprovers = await dbSAPPS.WorkflowApprover.findAll({
			where: { ...filterConditionsApprover, status: "Need Approval" },
			attributes: ["workflow_id"],
		});

		const workflowIds = workflowApprovers.map((wa) => wa.workflow_id);

		const filterConditions = {
			status: "Need Approval",
			doctype_id: PERMIT_EASE_DOCTYPE_ID,
		};

		if (
			params.access_read_all_data === true ||
			params.access_read_all_data === "true" ||
			params.administrator_of_hr === true ||
			params.administrator_of_hr === "true"
		) {
			filterConditions.id = { [Op.ne]: null };
		} else {
			if (workflowIds.length > 0) {
				filterConditions.id = { [Op.in]: workflowIds };
			} else {
				return {
					permitEases: [],
					success: true,
					message: "Loaded successfully!",
				};
			}
		}

		const workflows = await dbSAPPS.Workflow.findAll({
			where: filterConditions,
			order: [["modified", "DESC"]],
			attributes: ["id", "doc_id", "doctype_id", "status", "modified"],
			include: [
				{
					model: dbSAPPS.WorkflowApprover,
					as: "workflowapprovers",
					attributes: ["id", "workflow_id", "designation_id", "territory_id", "status"],
				},
			],
		});

		const docIds = [...new Set(workflows.map((w) => w.doc_id).filter(Boolean))];
		if (docIds.length === 0) {
			return {
				permitEases: [],
				success: true,
				message: "Loaded successfully!",
			};
		}

		const peFilter = { id: { [Op.in]: docIds } };
		if (params.employeesId && Array.isArray(params.employeesId) && params.employeesId.length > 0) {
			peFilter.employee_id = { [Op.in]: params.employeesId };
		}

		const permitEases = await dbSAPPS.PermitEase.findAll({
			where: peFilter,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.Company,
					as: "company",
					attributes: ["id", "display_name", "name"],
				},
				{
					model: dbSAPPS.Employee,
					as: "employee",
					attributes: ["id", "employee_name", "employee_number"],
				},
			],
		});

		const workflowByDocId = {};
		workflows.forEach((w) => {
			workflowByDocId[w.doc_id] = w;
		});

		const list = permitEases.map((pe) => {
			const w = workflowByDocId[pe.id];
			return {
				...pe.dataValues,
				workflow_id: w ? w.id : null,
				workflow: w ? {
					id: w.id,
					doc_id: w.doc_id,
					doctype_id: w.doctype_id,
					status: w.status,
					modified: w.modified
				} : null,
				workflowapprovers: w?.workflowapprovers || [],
				employee_name: pe?.employee?.employee_name,
				company_name: pe?.company?.display_name,
			};
		});

		return {
			permitEases: list,
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		const errorMessage = error?.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
			permitEases: [],
		};
	}
}
