export function useConcerts(options = {}) {
    const queryString = computed(() => {
        const locale = unref(options.locale) ?? "fr-FR"
        const sort = unref(options.sort) ?? null
        const pageSize = unref(options.pageSize) ?? 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 (typeof pageSize === "number") {
            query.set("pagination[pageSize]", String(pageSize))
        }
        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__/concerts?${queryString.value}`,
        {
            server: true,
            key: () => `concerts:${queryString.value}`,
            watch: [queryString],
        }
    )

    const concerts = computed(() => {
        const rows = (data.value?.data || []).map(normalizeConcert)
        let list = rows.sort(compareByRepresentationDate)

        const upcomingOnly = Boolean(unref(options.upcomingOnly) ?? false)
        if (upcomingOnly) {
            const todayStart = new Date()
            todayStart.setHours(0, 0, 0, 0)
            list = list.filter((c) => {
                const d = getFirstRepresentationDate(c)
                return d ? d >= todayStart : false
            })
        }

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

        return list
    })

    return {
        concerts,
        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 normalizeConcert(item) {
    const a = item.attributes || item || {}

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

// tri par date de représentation
function compareByRepresentationDate(a, b) {
    const da = getFirstRepresentationDate(a)
    const db = getFirstRepresentationDate(b)
    if (!da && !db) return 0
    if (!da) return 1
    if (!db) return -1
    return da - db
}

function getFirstRepresentationDate(concert) {
    const reps = concert?.representation_concert || []
    let earliest = null
    reps.forEach((r) => {
        const iso = r?.date_debut_representation
        if (!iso) return
        const d = new Date(iso)
        if (!earliest || d < earliest) earliest = d
    })
    return earliest
}
