import { fetchResource, readSession } from "./api";

export const PERSONNEL_PERMISSION_CODES = {
  SALES_ORDER: "MENU_SALES_PLANNING",
  PURCHASE_ORDER: "MENU_PURCHASE_ORDER",
  PURCHASE_RECEIPT: "MENU_PURCHASE_RECEIPT",
  INVENTORY_LEDGER: "MENU_INVENTORY_LEDGER",
  DELIVERY_MANAGEMENT: "MENU_DELIVERY_MANAGEMENT",
  EQUIPMENT_MANAGEMENT: "MENU_EQUIPMENT_MANAGEMENT"
};

export function normalizeEmployeeOption(row) {
  return {
    id: Number(row.employee_id ?? row.id),
    employee_id: Number(row.employee_id ?? row.id),
    employee_name: row.employee_name || row.name || "",
    mobile: row.mobile || "",
    dept_name: row.dept_name || "",
    job_title: row.job_title || "",
    username: row.username || "",
    role_names: Array.isArray(row.role_names) ? row.role_names : [],
    permission_codes: Array.isArray(row.permission_codes) ? row.permission_codes : [],
    has_system_user: Boolean(row.has_system_user)
  };
}

export async function fetchPermissionEmployeeOptions(permissionCode, limit = 500) {
  const params = new URLSearchParams({
    permission_code: permissionCode,
    limit: String(limit)
  });
  const rows = await fetchResource(`/master-data/employee-options?${params.toString()}`, []);
  return Array.isArray(rows) ? rows.map(normalizeEmployeeOption) : [];
}

export function defaultEmployeeIdFromSession(options) {
  const currentEmployeeId = readSession()?.employee_id;
  if (!currentEmployeeId) {
    return "";
  }
  const matched = options.find((employee) => String(employee.employee_id) === String(currentEmployeeId));
  return matched ? matched.employee_id : "";
}

export function employeeOptionLabel(employee) {
  const extra = [employee.dept_name, employee.role_names?.join("、")].filter(Boolean).join(" · ");
  return extra ? `${employee.employee_name} · ${extra}` : employee.employee_name;
}
