import { apiRequest, clearSession, saveSession } from './api';
import type { ApiEnvelope, CurrentUser } from '@/types';

export async function sendSmsCode(phone: string, purpose: 'login' | 'bind_phone' = 'login') {
  return apiRequest<ApiEnvelope<never>>('/api/auth/sms/send', {
    method: 'POST',
    body: { phone, purpose },
    tenantId: null,
    authMode: 'none',
  });
}

export async function verifySmsCode(phone: string, code: string, purpose: 'login' | 'bind_phone' = 'login') {
  const payload = await apiRequest<ApiEnvelope<CurrentUser>>('/api/auth/sms/verify', {
    method: 'POST',
    body: { phone, code, purpose },
    authMode: 'none',
  });
  if (payload.session?.token) saveSession(payload.session);
  return payload;
}

export async function loadCurrentUser() {
  return apiRequest<ApiEnvelope<CurrentUser>>('/api/auth/me');
}

export async function logout() {
  try {
    await apiRequest('/api/auth/logout', { method: 'POST' });
  } finally {
    clearSession();
  }
}
