import { client, DirectusError } from './client.js'

export async function uploadFile(file, options = {}) {
    const formData = new FormData()
    formData.append('file', file)

    if (options.folder) {
        formData.append('folder', options.folder)
    }

    const response = await fetch(`${client.baseUrl}/files`, {
        method: 'POST',
        headers: client.accessToken ? { 'Authorization': `Bearer ${client.accessToken}` } : {},
        body: formData
    })

    if (!response.ok) {
        const error = await response.json().catch(() => ({}))
        throw new DirectusError(response.status, 'Upload failed', error)
    }

    const result = await response.json()
    return result.data
}

export async function uploadMultipleFiles(files, options = {}) {
    const uploads = Array.from(files).map(file => uploadFile(file, options))
    return Promise.all(uploads)
}

export function getFileUrl(fileId, options = {}) {
    if (!fileId) return null

    const params = new URLSearchParams()

    if (options.width) params.set('width', options.width)
    if (options.height) params.set('height', options.height)
    if (options.fit) params.set('fit', options.fit)
    if (options.quality) params.set('quality', options.quality)
    if (options.format) params.set('format', options.format)

    const queryString = params.toString()
    return `${client.baseUrl}/assets/${fileId}${queryString ? '?' + queryString : ''}`
}

export function getThumbnailUrl(fileId, size = 300) {
    return getFileUrl(fileId, { width: size, height: size, fit: 'cover', format: 'webp', quality: 80 })
}
