import * as SecureStore from "expo-secure-store";
import { router } from "expo-router";
import { env } from "@haushaltsApp/env/native";
import { useAuthStore } from "../stores/auth.store";

const BASE_URL = env.EXPO_PUBLIC_SERVER_URL;
// expoClient plugin stores session token under "<storagePrefix>.session_token"
const TOKEN_KEY = "haushaltsapp.session_token";

export async function apiRequest<T>(
  path: string,
  options: RequestInit = {},
): Promise<T> {
  const householdId = useAuthStore.getState().activeHouseholdId;
  const token = await SecureStore.getItemAsync(TOKEN_KEY);

  const response = await fetch(`${BASE_URL}${path}`, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(householdId ? { "x-household-id": householdId } : {}),
      ...options.headers,
    },
    credentials: "include",
  });

  if (response.status === 401) {
    await SecureStore.deleteItemAsync(TOKEN_KEY);
    useAuthStore.getState().clearSession();
    router.replace("/(auth)/login");
    throw new Error("Unauthorized");
  }

  if (!response.ok) {
    const error = await response.json().catch(() => ({ error: "Unknown error" }));
    throw new Error((error as { error: string }).error ?? `HTTP ${response.status}`);
  }

  return response.json() as Promise<T>;
}
