import { api } from '@/core/services/api'
import type {
  UpdatePasswordPayload,
  UpdatePasswordResponse,
  UpdateProfilePayload,
  UpdateProfileResponse,
} from '../types/profile.types'

function appendIfDefined(formData: FormData, key: string, value: string | undefined) {
  if (value !== undefined && value !== '') {
    formData.append(key, value)
  }
}

export async function uploadProfileImage(image: File): Promise<UpdateProfileResponse> {
  const formData = new FormData()
  formData.append('image', image)

  const { data } = await api.post<UpdateProfileResponse>('/v1/profile', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  })
  return data
}

export async function updateProfile(payload: UpdateProfilePayload): Promise<UpdateProfileResponse> {
  const hasImage = payload.image instanceof File

  if (hasImage) {
    const formData = new FormData()
    formData.append('name', payload.name!.trim())
    appendIfDefined(formData, 'ic_number', payload.ic_number)
    appendIfDefined(formData, 'position', payload.position)
    appendIfDefined(formData, 'phone_number', payload.phone_number)
    appendIfDefined(formData, 'gender', payload.gender)
    appendIfDefined(formData, 'marriage_status', payload.marriage_status)
    appendIfDefined(formData, 'birth_date', payload.birth_date)
    appendIfDefined(formData, 'birth_place', payload.birth_place)
    formData.append('image', payload.image!)

    const { data } = await api.post<UpdateProfileResponse>('/v1/profile', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    return data
  }

  const body: Record<string, string> = {
    name: payload.name!.trim(),
  }

  if (payload.ic_number?.trim()) body.ic_number = payload.ic_number.trim()
  if (payload.position?.trim()) body.position = payload.position.trim()
  if (payload.phone_number?.trim()) body.phone_number = payload.phone_number.trim()
  if (payload.gender?.trim()) body.gender = payload.gender.trim()
  if (payload.marriage_status?.trim()) body.marriage_status = payload.marriage_status.trim()
  if (payload.birth_date?.trim()) body.birth_date = payload.birth_date.trim()
  if (payload.birth_place?.trim()) body.birth_place = payload.birth_place.trim()

  const { data } = await api.post<UpdateProfileResponse>('/v1/profile', body)
  return data
}

export async function updatePassword(payload: UpdatePasswordPayload): Promise<UpdatePasswordResponse> {
  const { data } = await api.put<UpdatePasswordResponse>('/v1/profile/password', payload)
  return data
}
