import { defineStore } from "pinia"
import { useFetch } from '@/hooks/fetch'

import { Domains } from '@/types/api/domain'
import { buildQueryString } from "@/assets/utils"

interface DomainsStore extends Domains {
  loading: boolean
  error?: string
}

export const useDomainsStore = defineStore({
  id: 'domains',
  state: (): DomainsStore => ({
    domains: null,
    loading: false,
    error: undefined,
    // pagination
    page: 1,
    per_page: 20,
    total: 0,
    pages: 0,
    // criteria
    query: '',
    sort: '-id',
    filter: ''
  }),
  actions: {
    async nextPage() {
      if (this.page < this.pages) {
        return this.fetchDomains(this.page + 1)
      }
    },
    async prevPage() {
      if (this.page > 1) {
        return this.fetchDomains(this.page - 1)
      }
    },
    async updateCriteria(query = '', sort = '-id', filter = '') {
      this.query = query
      this.sort = sort
      this.filter = filter
      return this.fetchDomains(1, this.per_page)
    },
    async fetchDomains(page = 1, per_page = 20) {
      this.loading = true
      const { data, error, execute } = useFetch(buildQueryString('/domain', {
        page: page.toString(),
        per_page: per_page.toString(),
        q: this.query,
        sort: this.sort,
        filter: this.filter
      })).json<Domains>()
      await execute()
      this.loading = false
      if (error.value) {
        this.error = error.value
        console.error(error.value)
      } else {
        this.error = undefined
        if (data.value?.domains) {
          // HACKS!
          // @TODO remove when geo is fixed
          // const domains = data.value.domains.map(d => {
          //   // @ts-ignore
          //   d.geo_data = d.geo_data[0]
          //   return d
          // })
          // @TODO add when paging is un-implemented
          this.domains = data.value.domains //.slice(0, 50).sort((a, b) => a.results[a.results.length - 1].badness - b.results[b.results.length - 1].badness)
          // END HACKS
          this.page = data.value.page ?? 1
          this.per_page = data.value.per_page ?? 20
          this.total = data.value.total ?? 0
          this.pages = data.value.pages ?? 0
        } else {
          this.domains = null
          this.page = 1
          this.per_page = 20
          this.total = 0
          this.pages = 0
        }
      }
    }
  }
})
