import { apiFetch, saveTokens } from '@/src/api/client';
import type { LoginRequest, RegisterRequest, TokenResponse, UserInfo } from '@/src/types/auth';

export async function login(payload: LoginRequest): Promise<TokenResponse> {
  const tokens = await apiFetch<TokenResponse>('/auth/login', {
    method: 'POST',
    body: payload,
    skipAuth: true,
  });
  await saveTokens(tokens);
  return tokens;
}

export async function register(payload: RegisterRequest): Promise<TokenResponse> {
  const tokens = await apiFetch<TokenResponse>('/auth/register', {
    method: 'POST',
    body: payload,
    skipAuth: true,
  });
  await saveTokens(tokens);
  return tokens;
}

export async function fetchCurrentUser(): Promise<UserInfo> {
  return apiFetch<UserInfo>('/auth/me');
}

export async function logout(refresh: string | null): Promise<void> {
  if (refresh) {
    try {
      await apiFetch('/auth/logout', {
        method: 'POST',
        body: { refreshToken: refresh },
        skipAuth: true,
      });
    } catch {
      // best effort
    }
  }
}
