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

const ABSENCE_CLARIFICATION_DOCTYPE_ID = 104;

module.exports = {
	getAll,
};

/**
 * Get Absence Clarifications that need approval for dashboard Workflow Approval card.
 * Uses same approver logic as Workflows Inbox: workflow status "Need Approval", doctype 104,
 * and WorkflowApprover matches designation_id/territory_id (or read_all_data).
 * Optionally filter by employeesId (subordinat) 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),
				},
			});
		}

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

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

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

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

		const filterConditions = {
			status: "Need Approval",
			doctype_id: ABSENCE_CLARIFICATION_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"
		) {
			// Admin: all workflows Need Approval for doctype 104
			filterConditions.id = { [Op.ne]: null };
		} else {
			if (workflowIds.length > 0) {
				filterConditions.id = { [Op.in]: workflowIds };
			} else {
				return {
					absenceClarifications: [],
					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 {
				absenceClarifications: [],
				success: true,
				message: "Loaded successfully!",
			};
		}

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

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

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