import { type Ref, defineComponent, inject, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';

import { useAlertService } from '@/shared/alert/alert.service';
import { useDateFormat } from '@/shared/composables';
import { type IMessaggio } from '@/shared/model/messaggio.model';

import MessaggioService from './messaggio.service';

export default defineComponent({
  name: 'MessaggioDetails',
  setup() {
    const dateFormat = useDateFormat();
    const messaggioService = inject('messaggioService', () => new MessaggioService());
    const alertService = inject('alertService', () => useAlertService(), true);

    const route = useRoute();
    const router = useRouter();

    const previousState = () => router.go(-1);
    const messaggio: Ref<IMessaggio> = ref({});

    const retrieveMessaggio = async messaggioId => {
      try {
        const res = await messaggioService().find(messaggioId);
        messaggio.value = res;
      } catch (error) {
        alertService.showHttpError(error.response);
      }
    };

    if (route.params?.messaggioId) {
      retrieveMessaggio(route.params.messaggioId);
    }

    return {
      ...dateFormat,
      alertService,
      messaggio,

      previousState,
      t$: useI18n().t,
    };
  },
});
