import { queryOptions } from '@tanstack/react-query'
import { directusList, directusOne, directusSingleton } from './directus'
import type { Category, Globals, Menu, MenuRaw, PageEntity, Vendor, VendorListItem } from './types'

export const globalsQuery = queryOptions({
  queryKey: ['globals'],
  queryFn: () => directusSingleton<Globals>('globals', { fields: ['*'] }),
  staleTime: 5 * 60_000,
})

export const menusQuery = queryOptions({
  queryKey: ['menus'],
  queryFn: async (): Promise<Menu[]> => {
    const { data } = await directusList<MenuRaw>('menus', {
      fields: [
        '*',
        'menus_menu_items.sort',
        'menus_menu_items.menu_items_id.label',
        'menus_menu_items.menu_items_id.url',
        'menus_menu_items.menu_items_id.sort',
      ],
      limit: -1,
    })
    return data.map((m) => ({
      id: m.id,
      items: [...m.menus_menu_items].sort((a, b) => a.sort - b.sort).map((mm) => mm.menu_items_id),
    }))
  },
  staleTime: 5 * 60_000,
})

export const categoriesQuery = queryOptions({
  queryKey: ['categories', 'roots'],
  queryFn: async (): Promise<Category[]> => {
    const { data } = await directusList<Category>('categories', {
      fields: ['slug', 'name', 'subcategories.slug', 'subcategories.name'],
      sort: 'name',
      limit: -1,
      filter: { parent_id: { _null: true } },
    })
    return data
  },
  staleTime: 5 * 60_000,
})

export const pageBySlugQuery = (slug: string) =>
  queryOptions({
    queryKey: ['page', slug],
    queryFn: async (): Promise<PageEntity | undefined> => {
      return directusOne<PageEntity>('pages', {
        fields: ['slug', 'title', 'content'],
        filter: { slug: { _eq: slug } },
      })
    },
  })

export type VendorsQueryParams = {
  page: number
  perPage: number
  search: string
  category: string
}

export const vendorsListQuery = ({ page, perPage, search, category }: VendorsQueryParams) =>
  queryOptions({
    queryKey: ['vendors', { page, perPage, search, category }],
    queryFn: async () => {
      const filter =
        search || category
          ? {
              _and: [
                category ? { categories: { categories_id: { slug: { _eq: category } } } } : {},
                search
                  ? {
                      _or: (['name', 'description', 'long_description', 'city'] as const).map((f) => ({
                        [f]: { _contains: search },
                      })),
                    }
                  : {},
              ],
            }
          : undefined

      return directusList<VendorListItem>('vendors', {
        fields: ['*'],
        limit: perPage,
        page,
        sort: 'name',
        meta: ['filter_count'],
        filter,
      })
    },
    placeholderData: (prev) => prev,
  })

export const vendorBySlugQuery = (slug: string) =>
  queryOptions({
    queryKey: ['vendor', slug],
    queryFn: async (): Promise<Vendor | undefined> => {
      return directusOne<Vendor>('vendors', {
        fields: [
          '*',
          'categories.categories_id.slug',
          'categories.categories_id.name',
          'categories.categories_id.parent_id',
        ],
        filter: { slug: { _eq: slug } },
      })
    },
  })
