// frontend/composables/useDirectus.js
import axios from 'axios'

const DIRECTUS_API_URL = '/api/directus'
// Create a reusable axios instance with default config
const directusApi = axios.create({
  baseURL: DIRECTUS_API_URL,
  headers: {
    'Content-Type': 'application/json',
    // Add this if you're using static token authentication
    // 'Authorization': `Bearer YOUR_STATIC_TOKEN`
  }
})

export const useDirectus = () => {
  const fetchCollection = async (collection, params = {}) => {
    try {
      const response = await directusApi.get(`/items/${collection}`, { params })
      return response.data.data
    } catch (error) {
      console.error('Error fetching data from Directus:', error)
      throw error
    }
  }

  const createItem = async (collection, itemData) => {
    try {
      const response = await directusApi.post(`/items/${collection}`, itemData)
      return response.data.data
    } catch (error) {
      console.error('Error creating item in Directus:', error)
      throw error
    }
  }

  const updateItem = async (collection, itemId, itemData) => {
    try {
      const response = await directusApi.patch(`/items/${collection}/${itemId}`, itemData)
      return response.data.data
    } catch (error) {
      console.error('Error updating item in Directus:', error)
      throw error
    }
  }

  const deleteItem = async (collection, itemId) => {
    try {
      const response = await directusApi.delete(`/items/${collection}/${itemId}`)
      return response.data.data
    } catch (error) {
      console.error('Error deleting item from Directus:', error)
      throw error
    }
  }

  return {
    fetchCollection,
    createItem,
    updateItem,
    deleteItem
  }
}