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 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 fetchMonthEntries(fromIso, toIso) {
  await ensureCsrf();
  const res = await api.get("/api/hours/month-entries", {
    params: { from: fromIso, to: toIso },
  });
  const payload = unwrap(res.data);
  return Array.isArray(payload) ? payload : [];
}

/**
 * @param {string[]} dates
 * @param {number} hours
 * @param {"internal"|"project"|"task"|"customer"} registrationType
 * @param {{ internal_category_id?: number|null, hour_project_id?: number|null, hour_task_id?: number|null, customer_id?: number|null, description?: string }} options
 */
export async function addBulkHours(dates, hours, registrationType, options = {}) {
  await ensureCsrf();
  const res = await api.post("/api/hours/entries/bulk", {
    dates,
    hours,
    registration_type: registrationType,
    internal_category_id: options.internal_category_id ?? null,
    hour_project_id: options.hour_project_id ?? null,
    hour_task_id: options.hour_task_id ?? null,
    customer_id: options.customer_id ?? null,
    description: options.description ?? "",
  });
  return res.data;
}

/** @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;
}
