import { ref } from 'vue'
import { defineStore } from 'pinia'

export interface MediaSet {
  id: number
  name: string
  description: string
  iconImageUrl: string
}

interface SetsResponse {
  sets: MediaSet[]
}

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL as string

export const useMediaSetsStore = defineStore('mediaSets', () => {
  const sets = ref<MediaSet[]>([])
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  async function fetchSets(): Promise<void> {
    error.value = null
    isLoading.value = true

    try {
      const response = await fetch(`${API_BASE_URL}/api/sets`)

      if (!response.ok) {
        sets.value = []
        error.value = 'Could not load media sets'
        return
      }

      const data: SetsResponse = await response.json()
      sets.value = data.sets
    } catch {
      sets.value = []
      error.value = 'Network error - could not load media sets'
    } finally {
      isLoading.value = false
    }
  }

  return { sets, isLoading, error, fetchSets }
})
