const AUDIT_CREATE_API = "http://localhost/backend/api/audit/create.php";

export const createAuditLog = async ({
  aksi,
  target = "",
  keterangan = "",
}) => {
  try {
    const username = localStorage.getItem("username") || "Admin";
    const role = localStorage.getItem("role") || "admin";
    const userId = localStorage.getItem("user_id") || null;

    const res = await fetch(AUDIT_CREATE_API, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        user_id: userId ? Number(userId) : null,
        username,
        role,
        aksi,
        target,
        keterangan,
      }),
    });

    const result = await res.json();

    if (!result.success) {
      console.warn("Audit log gagal disimpan:", result.message);
    } else {
      window.dispatchEvent(new Event("audit-log-created"));
    }

    return result;
  } catch (err) {
    console.error("Gagal mengirim audit log:", err);
    return null;
  }
};