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

// Align with workflow.service.js to be robust across legacy doctypes.
const WORK_ACTIVITY_DOCTYPE_IDS = [230, 209];

module.exports = {
	getAll,
};

/**
 * Get Work Activities that need approval for dashboard Workflow Approval card.
 * Uses same approver logic as dashboards/absenceClarifications:
 * - WorkflowApprover status = "Need Approval" and matches designation_id/territory_id,
 * - Workflow status = "Need Approval" and doctype in WORK_ACTIVITY_DOCTYPE_IDS,
 * - Optionally filter by employeesId (subordinate scope).
 */
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: { [Op.in]: WORK_ACTIVITY_DOCTYPE_IDS },
		};

		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 { workActivities: [], 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 { workActivities: [], success: true, message: "Loaded successfully!" };
		}

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

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

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