<script setup lang="ts">
import log from "loglevel";
import { computed } from "vue";
import type { CompetenceCertificate } from "@/types";
import { useCurrentCourseSession } from "@/composables";
import CompetenceCertificateComponent from "@/pages/competence/CompetenceCertificateComponent.vue";
import { getPreviousRoute } from "@/router/history";
import { useQuery } from "@urql/vue";
import { COMPETENCE_NAVI_CERTIFICATE_QUERY } from "@/graphql/queries";
import { useUserStore } from "@/stores/user";

const props = defineProps<{
  courseSlug: string;
  certificateSlug: string;
  userId?: string;
}>();

log.debug("CompetenceCertificateDetailPage setup", props);

const user = useUserStore();
const courseSession = useCurrentCourseSession();

const certificatesQuery = useQuery({
  query: COMPETENCE_NAVI_CERTIFICATE_QUERY,
  variables: {
    courseSlug: props.courseSlug,
    courseSessionId: courseSession.value.id,
    userIds: [props.userId ?? user.id],
  },
});

const competenceCertificates = computed(() => {
  return (
    (certificatesQuery.data.value?.competence_certificate_list
      ?.competence_certificates as unknown as CompetenceCertificate[]) ?? []
  );
});

const certificate = computed(() => {
  return competenceCertificates.value.find((cc) =>
    cc.slug.endsWith(props.certificateSlug)
  );
});
</script>

<template>
  <div class="container-large">
    <nav class="py-4">
      <router-link
        :to="
          getPreviousRoute() || `/course/${props.courseSlug}/competence/certificates`
        "
        class="btn-text inline-flex items-center p-0"
        data-cy="back-button"
      >
        <it-icon-arrow-left class="-ml-1 mr-1 h-5 w-5"></it-icon-arrow-left>
        <span class="inline">{{ $t("general.back") }}</span>
      </router-link>
    </nav>
    <div v-if="certificate">
      <CompetenceCertificateComponent
        :competence-certificate="certificate"
        :detail-view="true"
      ></CompetenceCertificateComponent>
    </div>
  </div>
</template>

<style scoped></style>
