export function useArtistes(options = {}) {
    const queryString = computed(() => {
        const locale = unref(options.locale) ?? "fr-FR"
        const sort = unref(options.sort) ?? null
        const populate = unref(options.populate) ?? null
        const filters = unref(options.filters) ?? null

        const query = new URLSearchParams()
        query.set("locale", locale)
        if (sort) {
            query.set("sort[0]", sort)
        }
        if (populate && typeof populate === "object") {
            appendPopulate(query, populate)
        }
        if (filters && typeof filters === "object") {
            appendFilters(query, filters)
        }

        return query.toString()
    })

    const { data, pending, error, refresh } = useFetch(
        () => `/api/__strapi__/artistes?${queryString.value}`,
        {
            server: true,
            key: () => `artistes:${queryString.value}`,
            watch: [queryString],
        }
    )

    const artistes = computed(() => {
        let list = (data.value?.data || []).map(normalizeArtiste)

        const limit = unref(options.limit)
        if (typeof limit === "number") {
            list = list.slice(0, Math.max(0, limit))
        }

        return list
    })

    return {
        artistes,
        concerts: artistes,
        pending,
        error,
        refresh,
    }
}

function appendPopulate(query, populate, prefix = "populate") {
    Object.entries(populate).forEach(([key, value]) => {
        if (value === true) {
            query.set(`${prefix}[${key}]`, "true")
            return
        }
        if (value && typeof value === "object") {
            const entries = Object.entries(value)
            const allTrue = entries.length > 0 && entries.every(([, v]) => v === true)
            if (allTrue) {
                const list = entries.map(([k]) => k).join(",")
                query.set(`${prefix}[${key}][populate]`, list)
                return
            }
            appendPopulate(query, value, `${prefix}[${key}][populate]`)
        }
    })
}

function appendFilters(query, filters, prefix = "filters") {
    Object.entries(filters).forEach(([key, value]) => {
        if (value === null || value === undefined) return
        if (typeof value !== "object") {
            query.set(`${prefix}[${key}]`, String(value))
            return
        }
        Object.entries(value).forEach(([k, v]) => {
            if (v === null || v === undefined) return
            if (typeof v !== "object") {
                query.set(`${prefix}[${key}][${k}]`, String(v))
                return
            }
            appendFilters(query, v, `${prefix}[${key}][${k}]`)
        })
    })
}

function normalizeArtiste(item) {
    const a = item.attributes || item || {}

    return {
        id: item.id,
        ...a,
    }
}
