import { getToken, clearToken } from "../../lib/auth";

const API_BASE = "/api";

async function apiFetch(path: string, init: RequestInit = {}) {
  const token = getToken();
  const headers = new Headers(init.headers);

  headers.set("Accept", "application/json");
  if (init.body) headers.set("Content-Type", "application/json");
  if (token) headers.set("Authorization", `Bearer ${token}`);

  const res = await fetch(`${API_BASE}${path}`, { ...init, headers });

  if (res.status === 401) {
    clearToken();
    throw new Error("Unauthorized");
  }

  const text = await res.text();
  const data = text ? JSON.parse(text) : null;

  if (!res.ok) {
    const msg = data?.message || data?.error || text || `HTTP ${res.status}`;
    throw new Error(msg);
  }

  return data;
}

export type Expense = {
  id: number;
  title: string;
  amountCents: number;
  currency: string;
  category: string;
  expenseDate: string; // yyyy-mm-dd
  note?: string | null;
};

export async function listExpenses(params?: { from?: string; to?: string; page?: number; size?: number }) {
  const qs = new URLSearchParams();
  if (params?.from) qs.set("from", params.from);
  if (params?.to) qs.set("to", params.to);
  qs.set("page", String(params?.page ?? 0));
  qs.set("size", String(params?.size ?? 20));
  return apiFetch(`/expenses?${qs.toString()}`);
}

export async function createExpense(payload: Omit<Expense, "id">) {
  return apiFetch(`/expenses`, { method: "POST", body: JSON.stringify(payload) });
}

export async function updateExpense(id: number, payload: Omit<Expense, "id">) {
  return apiFetch(`/expenses/${id}`, { method: "PUT", body: JSON.stringify(payload) });
}

export async function deleteExpense(id: number) {
  return apiFetch(`/expenses/${id}`, { method: "DELETE" });
}
