import { get, post, put } from '@/lib/http/client'
import type { Role } from '@/types/auth'
import type { User, UpdateUserRequest } from '@/types/user'
import { getUserRoles } from './users'

export interface CurrentUserProfile {
  user: User
  roles: Role[]
}

export interface UpdatePasswordRequest {
  current_password: string
  new_password: string
  confirm_password: string
}

export interface AvatarUploadResponse {
  avatar_url: string
  thumbnail: string
  message: string
}

export interface TOTPStatusResponse {
  totp_enabled: boolean
}

export interface TOTPSetupResponse {
  secret: string
  qr_code_base64: string
  recovery_codes: string[]
}

export async function getCurrentProfile(userId: number): Promise<CurrentUserProfile> {
  const [user, roles] = await Promise.all([
    get<User>('/auth/userinfo'),
    getUserRoles(userId),
  ])

  return { user, roles }
}

export function updateProfile(userId: number, data: UpdateUserRequest): Promise<User> {
  return put<User>(`/users/${userId}`, data)
}

export function uploadAvatar(userId: number, file: File): Promise<AvatarUploadResponse> {
  const formData = new FormData()
  formData.append('avatar', file)
  return post<AvatarUploadResponse>(`/users/${userId}/avatar`, formData)
}

export function updatePassword(userId: number, data: UpdatePasswordRequest): Promise<void> {
  return put<void>(`/users/${userId}/password`, data)
}

export function getTOTPStatus(): Promise<TOTPStatusResponse> {
  return get<TOTPStatusResponse>('/auth/2fa/status')
}

export function getTOTPSetup(): Promise<TOTPSetupResponse> {
  return get<TOTPSetupResponse>('/auth/2fa/setup')
}

export function enableTOTP(code: string): Promise<void> {
  return post<void>('/auth/2fa/enable', { code })
}

export function disableTOTP(code: string): Promise<void> {
  return post<void>('/auth/2fa/disable', { code })
}
