import { api, ensureCsrf } from "../../../services/api.js";

const WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];

export { WEEKDAYS };

export async function fetchCurrentWeek(weekStartIso) {
  await ensureCsrf();
  const res = await api.get("/api/hours/week/current", {
    params: weekStartIso ? { week_start: weekStartIso } : {},
  });
  return unwrap(res.data);
}

export async function syncWeekLines(weekId, lines, removedIds = []) {
  await ensureCsrf();
  const res = await api.put(`/api/hours/weeks/${weekId}/lines`, {
    lines,
    removed_line_ids: removedIds,
  });
  return unwrap(res.data);
}

export async function submitWeek(weekId) {
  await ensureCsrf();
  const res = await api.post(`/api/hours/weeks/${weekId}/submit`, {});
  return {
    warnings: Array.isArray(res.data.warnings) ? res.data.warnings : [],
    week: unwrap(res.data),
  };
}

export async function fetchHistory(page = 1) {
  await ensureCsrf();
  const res = await api.get("/api/hours/history/weeks", { params: { page } });
  return res.data;
}

export async function fetchPendingApprovals() {
  await ensureCsrf();
  const res = await api.get("/api/hours/approvals/pending");
  return unwrapList(res.data);
}

export async function approveLine(lineId) {
  await ensureCsrf();
  const res = await api.post(`/api/hours/lines/${lineId}/approve`);
  return unwrap(res.data);
}

export async function rejectLine(lineId, reason) {
  await ensureCsrf();
  const res = await api.post(`/api/hours/lines/${lineId}/reject`, {
    reason,
  });
  return unwrap(res.data);
}

export async function fetchReportsSummary(query = {}) {
  await ensureCsrf();
  const res = await api.get("/api/hours/reports/summary", { params: query });
  const payload = res.data;

  // Laravel/API should return JSON; HTML (login page or debug Whoops) becomes a string and must not render as escaped JSON.
  if (typeof payload === "string") {
    const t = payload.trimStart();
    if (t.startsWith("<!DOCTYPE") || t.includes("<html")) {
      throw new Error(
        "The server returned a web page instead of report JSON. Confirm you are logged in with hours.reports.view and JSON API access.",
      );
    }
    throw new Error("Unexpected response (not JSON). Check the Hours reports API endpoint.");
  }
  if (payload == null || typeof payload !== "object" || Array.isArray(payload)) {
    throw new Error("Invalid report payload from server.");
  }

  return unwrap(payload);
}

export async function fetchRegistry() {
  await ensureCsrf();
  const [cats, customers, projects] = await Promise.all([
    api.get("/api/hours/registry/internal-categories"),
    api.get("/api/hours/registry/customers"),
    api.get("/api/hours/registry/projects"),
  ]);
  return {
    internalCategories: cats.data.data ?? [],
    customers: customers.data.data ?? [],
    projects: projects.data.data ?? [],
  };
}

/** @param {number} hourProjectId */
export async function fetchTasks(hourProjectId) {
  await ensureCsrf();
  const res = await api.get("/api/hours/registry/tasks", {
    params: { hour_project_id: hourProjectId },
  });
  const list = res.data?.data ?? [];
  return Array.isArray(list) ? list : [];
}

/** @param {string} fromIso @param {string} toIso */
export async function fetchWorkbenchDailyTotals(fromIso, toIso) {
  await ensureCsrf();
  const res = await api.get("/api/hours/workbench/daily-totals", {
    params: { from: fromIso, to: toIso },
  });
  const payload = unwrap(res.data);
  if (payload == null) {
    return [];
  }

  return Array.isArray(payload) ? payload : [];
}

function unwrap(payload) {
  return payload?.data ?? payload;
}

function unwrapList(payload) {
  if (payload?.data && Array.isArray(payload.data)) {
    return payload.data;
  }
  return [];
}
