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

export const useUploadCandidateFiles = (candidateId: string, category: DB.CandidateDocumentType, trigger: UseFormTrigger<any>) => {
    const queryClient = useQueryClient()
    const isLocalDev =
        typeof window !== 'undefined' &&
        ['localhost', '127.0.0.1'].includes(window.location.hostname)

    const uploadFiles = async (files: File[]) => {
        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) => {
            try {
                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(`Upload failed with status ${response.status}`)
                }
            } catch (error) {
                if (!isLocalDev) {
                    throw error
                }
                console.warn('Skipping blob upload in local dev:', error)
            }
        }))
        await Promise.all(uploadUrls.map(async ({ documentId }: any) => {
            await pikku().patch('/candidate/:candidateId/document/:documentId', { documentId, candidateId, uploaded: true })
        }))
        await queryClient.invalidateQueries({ queryKey: ['candidate'] })
        setTimeout(() => {
            trigger()
        }, 100)
    }

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

    return { uploadFiles, deleteFile }
}
