<script setup lang="ts">
import log from "loglevel";
import {
  COMPETENCE_NAVI_CERTIFICATE_FOR_USER_QUERY,
  COMPETENCE_NAVI_CERTIFICATE_QUERY,
} from "@/graphql/queries";
import { useQuery } from "@urql/vue";
import { computed, onMounted } from "vue";
import type { CompetenceCertificate } from "@/types";
import { useCurrentCourseSession } from "@/composables";
import CompetenceCertificateComponent from "@/pages/competence/CompetenceCertificateComponent.vue";
import {
  isCompetenceCertificateForUserQueryQuery,
  isCompetenceCertificateQueryQuery,
} from "@/services/competence";

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

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

const courseSession = useCurrentCourseSession();

const certificatesQuery = (() => {
  if (props.userId) {
    return useQuery({
      query: COMPETENCE_NAVI_CERTIFICATE_FOR_USER_QUERY,
      variables: {
        courseSlug: props.courseSlug,
        courseSessionId: courseSession.value.id,
        userId: props.userId,
      },
    });
  } else {
    return useQuery({
      query: COMPETENCE_NAVI_CERTIFICATE_QUERY,
      variables: {
        courseSlug: props.courseSlug,
        courseSessionId: courseSession.value.id,
      },
    });
  }
})();

const certificate = computed(() => {
  const data = certificatesQuery.data.value;
  if (!data) {
    return null;
  }

  let certificate;

  if (props.userId && isCompetenceCertificateForUserQueryQuery(data)) {
    certificate = data.competence_certificate_list_for_user;
  } else if (isCompetenceCertificateQueryQuery(data)) {
    certificate = data.competence_certificate_list;
  } else {
    // Handle case where data does not match expected types
    console.error("Data structure is not recognized!");
    return null;
  }

  if (!certificate) {
    return null;
  }

  return (
    (certificate.competence_certificates as unknown as CompetenceCertificate[]) ?? []
  ).find((cc) => cc.slug.endsWith(props.certificateSlug));
});

onMounted(async () => {
  // log.debug("AssignmentView mounted", props.assignmentId, props.userId);
});
</script>

<template>
  <div class="container-large">
    <nav class="py-4">
      <router-link
        class="btn-text inline-flex items-center pl-0"
        :to="`/course/${props.courseSlug}/competence/certificates`"
      >
        <it-icon-arrow-left />
        <span>{{ $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>
