const API_URL =
  (import.meta.env.VITE_API_URL as string | undefined) ?? "";

let authToken: string | null = localStorage.getItem("owner_token");

export const setToken = (token: string) => {
  authToken = token;
  localStorage.setItem("owner_token", token);
};

export const clearToken = () => {
  authToken = null;
  localStorage.removeItem("owner_token");
};

export const getToken = () => authToken;

export class ApiError extends Error {
  status: number;
  constructor(message: string, status: number) {
    super(message);
    this.status = status;
  }
}

export const api = async <T>(
  path: string,
  options: RequestInit = {},
): Promise<T> => {
  const headers = new Headers(options.headers);
  if (!headers.has("Content-Type") && options.body) {
    headers.set("Content-Type", "application/json");
  }
  if (authToken) headers.set("Authorization", `Bearer ${authToken}`);

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

  if (res.status === 401) {
    clearToken();
    throw new ApiError("Session expired. Please sign in again.", 401);
  }

  const body = await res.json().catch(() => ({}));

  if (!res.ok) {
    throw new ApiError(body.error ?? `Request failed (${res.status})`, res.status);
  }

  return body as T;
};
