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

const WORK_ACTIVITY_PLAN_DOCTYPE_ID = 246;

module.exports = {
	getAll,
};

/**
 * Get Work Activity Plans that need approval for dashboard Workflow Approval card.
 * Same logic as dashboards/absenceClarifications (approver-based).
 */
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 workflowFilter = {
			status: "Need Approval",
			doctype_id: WORK_ACTIVITY_PLAN_DOCTYPE_ID,
		};

		const isAdmin =
			params.access_read_all_data === true ||
			params.access_read_all_data === "true" ||
			params.administrator_of_hr === true ||
			params.administrator_of_hr === "true";

		if (!isAdmin) {
			if (workflowIds.length > 0) {
				workflowFilter.id = { [Op.in]: workflowIds };
			} else {
				return { workActivityPlans: [], success: true, message: "Loaded successfully!" };
			}
		}

		const workflows = await dbSAPPS.Workflow.findAll({
			where: workflowFilter,
			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 { workActivityPlans: [], success: true, message: "Loaded successfully!" };
		}

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

		const workActivityPlans = await dbSAPPS.WorkActivityPlan.findAll({
			where: planFilter,
			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 = workActivityPlans.map((p) => {
			const w = workflowByDocId[p.id];
			return {
				...p.dataValues,
				workflow_id: w ? w.id : null,
				doctype_id: w ? w.doctype_id : null,
				workflowapprovers: w?.workflowapprovers || [],
				employee_name: p?.employee?.employee_name,
				company_name: p?.company?.display_name,
			};
		});

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