<!--
Cotisation bar

Barre d'alerte qui s'affiche pour donner l'état de la cotisation
-->

<template>
  <main>
    <UiSystemBar
        v-if="alert !== null"
        :text="$t(alert.text)"
        icon="fas fa-info-circle"
        :on-click="alert.callback"
        class="theme-info"
    />
  </main>
</template>

<script setup lang="ts">
import {useOrganizationProfileStore} from "~/stores/organizationProfile";
import {Ref} from "vue";
import UrlUtils from "~/services/utils/urlUtils";
import {ALERT_STATE_COTISATION} from "~/types/enum/enums";
import {useEntityFetch} from "~/composables/data/useEntityFetch";
import Cotisation from "~/models/Organization/Cotisation";

const organizationProfile = useOrganizationProfileStore()

const runtimeConfig = useRuntimeConfig()
const baseLegacyUrl: string = runtimeConfig.baseUrlAdminLegacy

const cotisationYear: Ref<number | null> = ref(null)

/**
 * Redirige l'utilisateur vers la page des cotisations
 */
const goToCotisation = () => {
  if (!organizationProfile.id) {
    throw new Error('missing organization id')
  }
  window.location.href = UrlUtils.join(baseLegacyUrl, '/cotisation/cotisation_steps', organizationProfile.id, 'steps/1')
}

/**
 * Ouvre la page facturation dans un nouvel onglet
 */
const openInvoiceWindow = () => {
  if (!cotisationYear.value) {
    throw new Error('no cotisation year defined')
  }
  window.open(UrlUtils.join(baseLegacyUrl, 'cotisation/invoice', cotisationYear.value), '_blank')
}

/**
 * Redirige l'utilisateur vers la page des assurances
 */
const goToInsurancePage = () => {
  window.location.href = UrlUtils.join(baseLegacyUrl, 'cotisation/insuranceedit')
}

/**
 * Redirige (dans un nouvel onglet) l'utilsateur vers le site web de la CMF
 */
const openCmfSubscriptionPage = () => {
  window.open('https://www.cmf-musique.org/services/assurances/assurance-de-groupe/', '_blank')
}

// On récupère l'état des cotisations via l'API
if (!organizationProfile.id) {
  throw new Error('missing organization id')
}

const { fetch } = useEntityFetch()
const { data: cotisation } = await fetch(Cotisation, organizationProfile.id)

interface Alert {
  text: string
  callback: () => void
}

const alert: Ref<Alert | null> = ref(null)

if (cotisation.value !== null) {
  cotisationYear.value = cotisation.value.cotisationYear

  const mapping: Record<ALERT_STATE_COTISATION, Alert> = {
    'AFFILIATION': { text: 'cotisation_access', callback: goToCotisation },
    'INVOICE': { text: 'upload_cotisation_invoice', callback: openInvoiceWindow },
    'INSURANCE': { text: 'renew_insurance_cmf', callback: goToInsurancePage },
    'ADVERTISINGINSURANCE': { text: 'insurance_cmf_subscription', callback: openCmfSubscriptionPage },
  }

  alert.value = mapping[cotisation.value.alertState as ALERT_STATE_COTISATION]
}




</script>

<style scoped lang="scss">
  :deep(.clickable:hover) {
    text-decoration: none !important;
  }
</style>
