"use client";

/** Client-side token handling for the deployed (REQUIRE_AUTH=true) mode. */

const KEY = "slab_token";

export const getToken = (): string | null =>
  typeof window === "undefined" ? null : window.localStorage.getItem(KEY);

export const setToken = (t: string) => window.localStorage.setItem(KEY, t);

export const clearToken = () => window.localStorage.removeItem(KEY);

export const isSignedIn = (): boolean => !!getToken();

const BASE = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000";

export async function login(email: string, password: string): Promise<string | null> {
  const body = new URLSearchParams({ username: email, password });
  const res = await fetch(`${BASE}/api/auth/login`, { method: "POST", body });
  if (!res.ok) {
    const detail = (await res.json().catch(() => null))?.detail;
    throw new Error(typeof detail === "string" ? detail : "Sign-in failed");
  }
  const token = (await res.json()).access_token as string;
  setToken(token);
  return token;
}

export async function register(email: string, password: string): Promise<void> {
  const res = await fetch(`${BASE}/api/auth/register`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password }),
  });
  if (!res.ok) {
    const detail = (await res.json().catch(() => null))?.detail;
    throw new Error(typeof detail === "string" ? detail : "Registration failed");
  }
}
