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 IStruttura } from '@/shared/model/struttura.model';

import StrutturaService from './struttura.service';

export default defineComponent({
  name: 'StrutturaDetails',
  setup() {
    const dateFormat = useDateFormat();
    const strutturaService = inject('strutturaService', () => new StrutturaService());
    const alertService = inject('alertService', () => useAlertService(), true);

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

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

    const retrieveStruttura = async strutturaId => {
      try {
        const res = await strutturaService().find(strutturaId);
        struttura.value = res;
      } catch (error) {
        alertService.showHttpError(error.response);
      }
    };

    if (route.params?.strutturaId) {
      retrieveStruttura(route.params.strutturaId);
    }

    return {
      ...dateFormat,
      alertService,
      struttura,

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