import { apiRequest, setAccessToken } from '@/shared/api/client'
import type { AuthResponse, RegistrationStatus } from '@/shared/api/types'
import { useAuthStore } from './store'

/** Публично: включена ли открытая регистрация (для страниц входа/регистрации). */
export function fetchRegistrationStatus() {
  return apiRequest<RegistrationStatus>('/auth/registration')
}

export function login(userName: string, password: string) {
  return apiRequest<AuthResponse>('/auth/login', { method: 'POST', body: { userName, password } })
}

export function register(userName: string, password: string) {
  return apiRequest<AuthResponse>('/auth/register', {
    method: 'POST',
    body: { userName, password },
  })
}

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

export function changePassword(currentPassword: string, newPassword: string) {
  return apiRequest<void>('/auth/change-password', {
    method: 'POST',
    body: { currentPassword, newPassword },
  })
}

export function changeUserName(newUserName: string) {
  return apiRequest<void>('/auth/change-username', { method: 'POST', body: { newUserName } })
}

export function deleteAccount() {
  return apiRequest<void>('/auth/me', { method: 'DELETE' })
}

export function applyAuthResponse(auth: AuthResponse) {
  setAccessToken(auth.accessToken)
  useAuthStore.getState().setUser(auth.user)
}

/** Тихая попытка восстановить сессию по refresh-cookie при загрузке приложения. */
export async function bootstrapSession() {
  try {
    const auth = await apiRequest<AuthResponse>('/auth/refresh', {
      method: 'POST',
      skipRefresh: true,
    })
    applyAuthResponse(auth)
  } catch {
    setAccessToken(null)
    useAuthStore.getState().setUser(null)
  } finally {
    useAuthStore.getState().finishBootstrap()
  }
}

export function clearSession() {
  setAccessToken(null)
  useAuthStore.getState().setUser(null)
}
