<template>
  <div class="search">
    <ul class="search-results" v-if="results">
      <li v-for="[identity, result] in Object.entries(results)" :key="identity">
        <SearchResult :result="result" />
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import SearchResult from "@/components/SearchResult.vue";
import { ListingResult } from "@/types/base";
import { construct } from "@/utils";
import useSWRV from "swrv";
import { defineComponent } from "vue";
import { useRoute } from "vue-router";
import { fetcher } from "../utils";

export default defineComponent({
  name: "Search",
  components: { SearchResult },
  props: {
    searchQuery: {
      type: String,
      required: true,
    },
  },
  setup() {
    const route = useRoute();
    const { data } = useSWRV<ListingResult | unknown>(() => {
      let query = route.query.q as string | undefined;
      if (query && query !== "") {
        const ueQuery = construct("(matches ? ? (contains #))", [query]);
        return `/api/obj?query=${ueQuery}`;
      }
      return null;
    }, fetcher);

    return {
      results: data,
    };
  },
});
</script>

<style lang="scss">
.search-results {
  display: flex;
  flex-wrap: wrap;

  list-style: none;

  li {
    display: block;
    width: calc(100% / 6);
  }
}
</style>
