const AUTH_BASE = '/api/kcg/auth';

export interface AuthUser {
  email: string;
  name: string;
  picture?: string;
}

export async function googleLogin(credential: string): Promise<AuthUser> {
  const res = await fetch(`${AUTH_BASE}/google`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ credential }),
  });

  if (!res.ok) {
    const body = await res.json().catch(() => ({}));
    throw new Error(body.message ?? 'Login failed');
  }

  return res.json();
}

export async function getMe(): Promise<AuthUser> {
  const res = await fetch(`${AUTH_BASE}/me`, {
    credentials: 'include',
  });

  if (!res.ok) {
    throw new Error('Not authenticated');
  }

  return res.json();
}

export async function logout(): Promise<void> {
  await fetch(`${AUTH_BASE}/logout`, {
    method: 'POST',
    credentials: 'include',
  });
}
