// ===== MyEmpInfo — Data layer (fetches from /api/*) =====
//
// Exposes:
//   window.MEI_DATA  — { DEPARTMENTS, EMPLOYEES, ACTIVITY } (populated after load)
//   window.MEI_API   — fetch helpers for CRUD
//   window.MEI_STATS — populated dashboard stats from API (optional)

window.MEI_DATA = { DEPARTMENTS: [], EMPLOYEES: [], ACTIVITY: [] };
window.MEI_STATS = null;

async function jsonOrThrow(res) {
  if (!res.ok) {
    const body = await res.text().catch(() => "");
    throw new Error(`HTTP ${res.status}: ${body}`);
  }
  return res.json();
}

window.MEI_API = {
  async loadAll() {
    const [depts, emps, activity, stats] = await Promise.all([
      fetch("/api/departments").then(jsonOrThrow),
      fetch("/api/employees").then(jsonOrThrow),
      fetch("/api/activity-log?limit=20").then(jsonOrThrow),
      fetch("/api/dashboard/stats").then(jsonOrThrow).catch(() => null),
    ]);
    window.MEI_DATA = {
      DEPARTMENTS: depts,
      EMPLOYEES:   emps,
      ACTIVITY:    activity.map(a => ({ ...a, time: relativeTime(a.createdAt) })),
    };
    window.MEI_STATS = stats;
    return window.MEI_DATA;
  },

  async createEmployee(payload) {
    const res = await fetch("/api/employees", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(payload),
    });
    return jsonOrThrow(res);
  },

  async updateEmployee(id, patch) {
    const res = await fetch(`/api/employees/${encodeURIComponent(id)}`, {
      method: "PATCH",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(patch),
    });
    return jsonOrThrow(res);
  },

  async resignEmployee(id) {
    const res = await fetch(`/api/employees/${encodeURIComponent(id)}`, {
      method: "DELETE",
    });
    return jsonOrThrow(res);
  },

  async me() {
    return fetch("/api/me").then(jsonOrThrow).catch(() => ({ email: "guest", name: "Guest" }));
  },
};

function relativeTime(iso) {
  if (!iso) return "";
  const t = new Date(iso.replace(" ", "T") + "Z").getTime();
  const diff = Math.max(0, Date.now() - t);
  const mins = Math.floor(diff / 60000);
  if (mins < 1)   return "เมื่อสักครู่";
  if (mins < 60)  return `${mins} นาทีที่แล้ว`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24)   return `${hrs} ชั่วโมงที่แล้ว`;
  const days = Math.floor(hrs / 24);
  if (days === 1) return "เมื่อวาน";
  if (days < 7)   return `${days} วันที่แล้ว`;
  const wks = Math.floor(days / 7);
  if (wks < 5)    return `${wks} สัปดาห์ที่แล้ว`;
  const mos = Math.floor(days / 30);
  return `${mos} เดือนที่แล้ว`;
}
