// FILE: src/middleware/abac.js
// ABAC: Attribute-Based Access Control middleware helpers
// - Project-scoped access control base on user_project_roles + permissions
// - Requires req.user.roles and req.user.permissions to be populated (e.g. via auth.js with enrichment)
// - Uses UserProjectRole model to check project membership
// Helper ABAC เสริมบางเคส (ถ้าต้องการฟิลเตอร์/บังคับ project_id ตรง ๆ)
// หมายเหตุ: โดยหลักแล้วคุณควรใช้ requirePerm() ที่บังคับ ABAC อัตโนมัติจาก permissions.scope_level

export function projectScopedViewFallback(moduleName) {
  // ใช้ในเคส legacy เท่านั้น
  return async (req, res, next) => {
    const p = req.principal;
    if (!p) return res.status(401).json({ error: "Unauthenticated" });

    const hasViewPerm = p.can?.(`${moduleName}.view`) || p.permissions?.has?.(`${moduleName}.view`);
    if (p.is_superadmin) return next();

    const qProjectId = req.query?.project_id ? Number(req.query.project_id) : null;

    if (qProjectId) {
      if (hasViewPerm || p.inProject(qProjectId)) return next();
      return res.status(403).json({ error: "FORBIDDEN_PROJECT" });
    } else {
      if (hasViewPerm) return next();
      if (!p.project_ids?.length) return res.status(403).json({ error: "FORBIDDEN_PROJECT" });
      req.abac = req.abac || {};
      req.abac.filterProjectIds = p.project_ids;
      return next();
    }
  };
}

export function requireProjectIdQuery() {
  return (req, res, next) => {
    const p = req.principal;
    if (!p) return res.status(401).json({ error: "Unauthenticated" });
    if (p.is_superadmin) return next();
    const qProjectId = req.query?.project_id ? Number(req.query.project_id) : null;
    if (!qProjectId) return res.status(400).json({ error: "project_id query required" });
    next();
  };
}

