export const SESSION_COOKIE = 'hidrotintas_admin_token';

const sessionSeconds = 60 * 60 * 8;

function apiUrl() {
  return (process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3001').replace(/\/$/, '');
}

function cookiePath() {
  return process.env.NEXT_PUBLIC_BASE_PATH || '/';
}

export function readSessionToken() {
  if (typeof document === 'undefined') return '';
  const prefix = `${SESSION_COOKIE}=`;
  const match = document.cookie.split('; ').find((item) => item.startsWith(prefix));
  return match ? decodeURIComponent(match.slice(prefix.length)) : '';
}

export function writeSessionToken(token: string) {
  const secure = window.location.protocol === 'https:' ? '; Secure' : '';
  document.cookie = `${SESSION_COOKIE}=${encodeURIComponent(token)}; Path=${cookiePath()}; Max-Age=${sessionSeconds}; SameSite=Lax${secure}`;
}

export function clearSession() {
  const secure = window.location.protocol === 'https:' ? '; Secure' : '';
  document.cookie = `${SESSION_COOKIE}=; Path=${cookiePath()}; Max-Age=0; SameSite=Lax${secure}`;
}

async function readError(response: Response) {
  try {
    const body = (await response.json()) as { message?: string | string[] };
    if (Array.isArray(body.message)) return body.message[0] ?? 'Não foi possível entrar.';
    if (body.message) return body.message;
  } catch {
    return 'Não foi possível entrar.';
  }
  return 'Não foi possível entrar.';
}

export async function login(email: string, password: string) {
  const response = await fetch(`${apiUrl()}/auth/login`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password }),
  });
  if (!response.ok) throw new Error(await readError(response));
  const { accessToken } = (await response.json()) as { accessToken: string };
  writeSessionToken(accessToken);
}

export async function fetchCurrentUser(token: string) {
  const response = await fetch(`${apiUrl()}/auth/me`, {
    headers: { Authorization: `Bearer ${token}` },
    cache: 'no-store',
  });
  if (!response.ok) throw new Error('Sessão expirada.');
  return response.json() as Promise<{ id: string; name: string; email: string }>;
}
