import { api, setTokens } from './http';

export interface AuthTokenData {
  access_token: string;
  refresh_token: string;
  expires_in: number;
  uid: string;
  token_type: string;
}

export interface RegisterData {
  challenge_id: string;
  expires_in: number;
  uid: string;
}

export async function login(tenantSlug: string, email: string, password: string) {
  const data = await api<AuthTokenData>('/api/v1/auth/login', {
    auth: false,
    method: 'POST',
    body: JSON.stringify({ tenant_slug: tenantSlug, email, password }),
  });
  setTokens(data.access_token, data.refresh_token);
  localStorage.setItem('uid', data.uid);
  return data;
}

export async function register(body: {
  tenant_slug: string;
  invite_code: string;
  email: string;
  password: string;
  display_name?: string;
  language?: string;
}) {
  return api<RegisterData>('/api/v1/auth/register', {
    auth: false,
    method: 'POST',
    body: JSON.stringify({
      ...body,
      accept_terms_version: '2025-01-01',
      marketing_opt_in: false,
    }),
  });
}

export async function registerConfirm(
  tenantSlug: string,
  challengeId: string,
  code: string,
) {
  const data = await api<AuthTokenData>('/api/v1/auth/register/confirm', {
    auth: false,
    method: 'POST',
    body: JSON.stringify({
      tenant_slug: tenantSlug,
      challenge_id: challengeId,
      code,
    }),
  });
  setTokens(data.access_token, data.refresh_token);
  localStorage.setItem('uid', data.uid);
  return data;
}

export async function registerResend(tenantSlug: string, challengeId: string) {
  return api<RegisterData>('/api/v1/auth/register/resend', {
    auth: false,
    method: 'POST',
    body: JSON.stringify({ tenant_slug: tenantSlug, challenge_id: challengeId }),
  });
}

export async function logout() {
  try {
    await api('/api/v1/auth/logout', { method: 'POST', body: '{}' });
  } finally {
    /* always clear local */
  }
}

export async function refreshToken() {
  const refresh = localStorage.getItem('refresh_token');
  if (!refresh) throw new Error('無 refresh token');
  const data = await api<AuthTokenData>('/api/v1/auth/token/refresh', {
    auth: false,
    method: 'POST',
    body: JSON.stringify({ refresh_token: refresh }),
  });
  setTokens(data.access_token, data.refresh_token);
  localStorage.setItem('uid', data.uid);
  return data;
}
