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 });
  return res.data;
}

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

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

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