// FILE: src/middleware/permissions.js
// Permission calculation and enrichment middleware
// - Computes effective permissions for a user based on their roles
// - Attaches permissions to req.user.permissions
// ใช้เฉพาะกรณีที่คุณยังมี stack Sequelize เดิมอยู่ และอยาก enrich จาก Role/Permission model
// โดยทั่วไป ถ้าคุณใช้ loadPrincipalMw() อยู่แล้ว สามารถไม่ใช้ไฟล์นี้ได้

import { Permission, UserRole, RolePermission } from "../db/sequelize.js";

export async function computeEffectivePermissions(user_id) {
  const userRoles = await UserRole.findAll({ where: { user_id } });
  const roleIds = userRoles.map((r) => r.role_id);
  if (!roleIds.length) return [];

  const rp = await RolePermission.findAll({ where: { role_id: roleIds } });
  const permIds = [...new Set(rp.map((x) => x.permission_id))];
  if (!permIds.length) return [];

  const perms = await Permission.findAll({ where: { permission_id: permIds } });
  // ใช้ perm_code ให้สอดคล้อง seed
  return [...new Set(perms.map((p) => p.perm_code))];
}

export function enrichPermissions() {
  return async (req, _res, next) => {
    const uid = req?.auth?.user_id || req?.user?.user_id;
    if (!uid) return next();
    try {
      const perms = await computeEffectivePermissions(uid);
      // อัปเดตทั้ง req.principal และ req.user (เผื่อโค้ดเก่า)
      req.principal = req.principal || {};
      req.principal.permissions = new Set(perms);
      req.user = req.user || {};
      req.user.permissions = perms;
    } catch {
      if (req.principal) req.principal.permissions = new Set();
      if (req.user) req.user.permissions = [];
    }
    next();
  };
}