"use client";

import { getApiBaseUrl } from "./constants";
import { getToken } from "./auth";

/** The browser's IANA timezone, sent to the API as `X-Timezone`. */
function browserTimezone(): Record<string, string> {
  const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
  return tz ? { "X-Timezone": tz } : {};
}

export type ApiResult<T> = {
  ok: boolean;
  data?: T;
  total?: number;
  message?: string;
  status: number;
};

type FetchOptions = {
  method?: string;
  body?: unknown;
  locale?: string;
  auth?: boolean;
};

export async function apiFetch<T = unknown>(
  path: string,
  options: FetchOptions = {},
): Promise<ApiResult<T>> {
  const { method = "GET", body, locale = "pl", auth = true } = options;
  const headers: Record<string, string> = {
    locale,
    "Content-Type": "application/json",
    ...browserTimezone(),
  };

  if (auth) {
    const token = getToken();
    if (token) headers.Authorization = `Bearer ${token}`;
  }

  const res = await fetch(`${getApiBaseUrl()}${path}`, {
    method,
    headers,
    body: body !== undefined ? JSON.stringify(body) : undefined,
    credentials: "include",
  }).catch(() => null);

  if (!res) {
    return {
      ok: false,
      status: 0,
      message: "Network error",
    };
  }

  const contentType = res.headers.get("content-type") ?? "";
  if (
    !contentType.includes("application/json") &&
    res.ok &&
    method === "GET"
  ) {
    return { ok: true, status: res.status, data: undefined };
  }

  let payload: { message?: string; data?: T; total?: number } = {};
  try {
    payload = (await res.json()) as typeof payload;
  } catch {
    payload = { message: res.statusText };
  }

  return {
    ok: res.ok,
    status: res.status,
    data: payload.data,
    total: payload.total,
    message: payload.message,
  };
}

export async function downloadExport(
  format: "pdf" | "xlsx" | "csv",
  period: "all" | "daily" | "monthly" | "yearly",
  locale: string,
) {
  const token = getToken();
  const url = `${getApiBaseUrl()}/driver-company/export?format=${format}&period=${period}`;
  const res = await fetch(url, {
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
      locale,
      ...browserTimezone(),
    },
    credentials: "include",
  });
  if (!res.ok) return false;
  const blob = await res.blob();
  const ext = format === "pdf" ? "pdf" : format === "csv" ? "csv" : "xlsx";
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = `export-${period}.${ext}`;
  link.click();
  URL.revokeObjectURL(link.href);
  return true;
}
