import apiClient from './client'
import type { Token, User, UserCreate, UserLogin, UserUpdate } from '@/types'

export const authApi = {
  async register(data: UserCreate): Promise<User> {
    const response = await apiClient.post<User>('/auth/register', data)
    return response.data
  },

  async login(data: UserLogin): Promise<Token> {
    const response = await apiClient.post<Token>('/auth/login/json', data)
    return response.data
  },

  async refresh(): Promise<Token> {
    const refreshToken = localStorage.getItem('refresh_token')
    const response = await apiClient.post<Token>('/auth/refresh', null, {
      headers: {
        Authorization: `Bearer ${refreshToken}`,
      },
    })
    return response.data
  },

  async me(): Promise<User> {
    const response = await apiClient.get<User>('/auth/me')
    return response.data
  },

  async logout(): Promise<void> {
    await apiClient.post('/auth/logout')
  },

  async changePassword(currentPassword: string, newPassword: string): Promise<void> {
    await apiClient.post('/auth/password/change', {
      current_password: currentPassword,
      new_password: newPassword,
    })
  },

  async forgotPassword(email: string): Promise<void> {
    await apiClient.post('/auth/password/forgot', { email })
  },

  async verifyResetToken(token: string): Promise<{ valid: boolean; email: string | null }> {
    const response = await apiClient.post<{ valid: boolean; email: string | null }>('/auth/password/verify-reset-token', { token })
    return response.data
  },

  async resetPassword(token: string, newPassword: string): Promise<void> {
    await apiClient.post('/auth/password/reset', {
      token,
      new_password: newPassword,
    })
  },

  async updateProfile(data: UserUpdate): Promise<User> {
    const response = await apiClient.patch<User>('/auth/me', data)
    return response.data
  },

  async getVerificationStatus(): Promise<{ enabled: boolean }> {
    const response = await apiClient.get<{ enabled: boolean }>('/auth/email/verification-status')
    return response.data
  },

  async sendVerificationEmail(): Promise<void> {
    await apiClient.post('/auth/email/send-verification')
  },

  async verifyEmail(token: string): Promise<void> {
    await apiClient.post('/auth/email/verify', { token })
  },
}

export default authApi
