import { apiFetch } from './client'
import { setAuthToken, getAuthToken } from './token'

// Re-export for convenience
export { setAuthToken, getAuthToken }

export interface User {
  id: string
  email: string
  display_name: string
  avatar_url?: string
  created_at: string
  updated_at: string
}

export interface AuthResponse {
  user: User
  access_token: string
}

export interface RegisterData {
  email: string
  password: string
  display_name: string
}

export interface LoginData {
  email: string
  password: string
}

export interface UpdateProfileData {
  display_name?: string
  avatar_url?: string
}

export interface ChangePasswordData {
  current_password: string
  new_password: string
}

export function register(data: RegisterData): Promise<AuthResponse> {
  return apiFetch<AuthResponse>('/auth/register', {
    method: 'POST',
    body: JSON.stringify(data),
  })
}

export function login(data: LoginData): Promise<AuthResponse> {
  return apiFetch<AuthResponse>('/auth/login', {
    method: 'POST',
    body: JSON.stringify(data),
  })
}

export function logout(): Promise<void> {
  return apiFetch<void>('/auth/logout', {
    method: 'POST',
  })
}

export function getMe(): Promise<User> {
  return apiFetch<User>('/auth/me')
}

export function updateProfile(data: UpdateProfileData): Promise<User> {
  return apiFetch<User>('/auth/me', {
    method: 'PUT',
    body: JSON.stringify(data),
  })
}

export function changePassword(data: ChangePasswordData): Promise<void> {
  return apiFetch<void>('/auth/me/password', {
    method: 'PUT',
    body: JSON.stringify(data),
  })
}

export function refreshToken(): Promise<AuthResponse> {
  return fetch('/api/auth/refresh', {
    method: 'POST',
    credentials: 'include',
  }).then((res) => {
    if (!res.ok) throw new Error('Refresh failed')
    return res.json()
  })
}
