import api from './api'

export const dataService = {
    getAssets: async (limit, offset, type) => {
        const params = { limit, offset }
        if (type && type !== 'all') params.type = type
        const response = await api.get('/assets', { params })
        return response.data
    },

    getAsset: async (id) => {
        const response = await api.get(`/assets/${id}`)
        return response.data
    },

    getCharacters: async () => {
        // Spec says /api/characters/ (with trailing slash) but usually client shouldn't matter too much if config is good,
        // but let's follow spec if strictly needed. Axios usually handles this.
        const response = await api.get('/characters/')
        return response.data
    },

    getCharacterById: async (id) => {
        const response = await api.get(`/characters/${id}`)
        return response.data
    },

    createCharacter: async (characterData) => {
        const response = await api.post('/characters/', characterData)
        return response.data
    },

    deleteCharacter: async (id) => {
        const response = await api.delete(`/characters/${id}`)
        return response.data
    },

    getAssetsByCharacterId: async (charId, limit, offset) => {
        const response = await api.get(`/characters/${charId}/assets`, { params: { limit, offset } })
        return response.data
    },

    uploadAsset: async (file, linkedCharId) => {
        const formData = new FormData()
        formData.append('file', file)
        if (linkedCharId) formData.append('linked_char_id', linkedCharId)
        
        const response = await api.post('/assets/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        return response.data
    },

    deleteAsset: async (id) => {
        const response = await api.delete(`/assets/${id}`)
        return response.data
    },

    deleteGeneration: async (id) => {
        const response = await api.delete(`/generations/${id}`)
        return response.data
    },

    generatePromptFromImage: async (files, prompt) => {
        const formData = new FormData()
        
        // Handle single or multiple files
        const fileArray = Array.isArray(files) ? files : [files]
        fileArray.forEach(file => {
            formData.append('images', file)
        })

        if (prompt) {
            formData.append('prompt', prompt)
        }
        
        const response = await api.post('/generations/prompt-from-image', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        
        return response.data.prompt
    }
}
