import { ref, type Ref } from "vue";
import { defineStore } from "pinia";
import type { AggItem, SearchResult } from "@/types/search.types";
import * as searchService from "@/services/search.service";
import type { SearchRequest } from "@/types/request.types";

export const useSearchStore = defineStore('search', () => {
  const result: Ref<SearchResult | null> = ref(null);
  const yearAggResult: Ref<AggItem[] | null> = ref(null);
  const authorAggResult: Ref<AggItem[] | null> = ref(null);
  const unitAggResult: Ref<AggItem[] | null> = ref(null);

  async function search(request: SearchRequest) {
    return searchService.search(request).then((resp) => {
      result.value = resp;
    })
  }

  async function aggYear(request: SearchRequest) {
    try {
      const params = { ...request, aggs: { year: { sort: "key/desc" } }, size: 0 }
      const resp = await searchService.search(params);
      yearAggResult.value = resp.aggs.year || [];
    } catch (err) {
      console.log(err);
    }
  }

  async function aggAuthor(request: SearchRequest) {
    try {
      const params = { ...request, aggs: { AU: { sort: "count/desc" } }, size: 0 }
      const resp = await searchService.search(params);
      authorAggResult.value = resp.aggs.AU || [];
    } catch (err) {
      console.log(err);
    }
  }

  async function aggUnit(request: SearchRequest) {
    try {
      const params = { ...request, aggs: { UN: { sort: "count/desc" } }, size: 0 }
      const resp = await searchService.search(params);
      unitAggResult.value = resp.aggs.UN || [];
    } catch (err) {
      console.error(err)
    }
  }

  return {
    result,
    yearAggResult,
    authorAggResult,
    unitAggResult,
    search,
    aggYear,
    aggAuthor,
    aggUnit,
  }
});
