import { pikku } from "@/pikku/http"
import type { DB } from '@heygermany/sdk'
import { useQueryClient } from "@tanstack/react-query"

export const useUploadBackOfficeCandidateFiles = (candidateId: string, category: DB.CandidateDocumentType) => {
  const queryClient = useQueryClient()

  const uploadFiles = async (files: File[]) => {
    if (!files.length) {
      return
    }

    const uploadUrls = await pikku().post('/candidate/:candidateId/document', {
      candidateId,
      documents: files.map((file) => ({
        fileName: file.name,
        size: file.size,
        contentType: file.type,
        category
      }))
    })

    await Promise.all(uploadUrls.map(async ({ uploadUrl }: any, index: number) => {
      const response = await fetch(uploadUrl, {
        method: 'PUT',
        body: files[index],
        cache: 'no-cache',
        mode: 'cors',
        credentials: 'include',
        headers: {
          'Content-Type': files[index].type,
          'Content-Disposition': 'inline'
        }
      })

      if (!response.ok) {
        throw new Error(`Failed to upload ${files[index].name}`)
      }
    }))

    await Promise.all(uploadUrls.map(async ({ documentId }: any) => {
      await pikku().patch('/candidate/:candidateId/document/:documentId', {
        documentId,
        candidateId,
        uploaded: true
      })
    }))

    await queryClient.invalidateQueries({
      queryKey: ['backoffice', 'candidate', candidateId]
    })
  }

  const deleteFile = async (documentId: string) => {
    await pikku().delete('/candidate/:candidateId/document/:documentId', {
      candidateId,
      documentId
    })

    await queryClient.invalidateQueries({
      queryKey: ['backoffice', 'candidate', candidateId]
    })
  }

  return { uploadFiles, deleteFile }
}
