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

import { useVuelidate } from '@vuelidate/core';

import UtenteAppService from '@/entities/utente-app/utente-app.service';
import { useAlertService } from '@/shared/alert/alert.service';
import { useDateFormat, useValidation } from '@/shared/composables';
import { AuditLog, type IAuditLog } from '@/shared/model/audit-log.model';
import { AzioneAudit } from '@/shared/model/enumerations/azione-audit.model';
import { TipoEntita } from '@/shared/model/enumerations/tipo-entita.model';
import { type IUtenteApp } from '@/shared/model/utente-app.model';

import AuditLogService from './audit-log.service';

export default defineComponent({
  name: 'AuditLogUpdate',
  setup() {
    const auditLogService = inject('auditLogService', () => new AuditLogService());
    const alertService = inject('alertService', () => useAlertService(), true);

    const auditLog: Ref<IAuditLog> = ref(new AuditLog());

    const utenteAppService = inject('utenteAppService', () => new UtenteAppService());

    const utenteApps: Ref<IUtenteApp[]> = ref([]);
    const tipoEntitaValues: Ref<string[]> = ref(Object.keys(TipoEntita));
    const azioneAuditValues: Ref<string[]> = ref(Object.keys(AzioneAudit));
    const isSaving = ref(false);
    const currentLanguage = inject('currentLanguage', () => computed(() => navigator.language ?? 'it'), true);

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

    const previousState = () => router.go(-1);

    const retrieveAuditLog = async auditLogId => {
      try {
        const res = await auditLogService().find(auditLogId);
        res.createdAt = new Date(res.createdAt);
        auditLog.value = res;
      } catch (error) {
        alertService.showHttpError(error.response);
      }
    };

    if (route.params?.auditLogId) {
      retrieveAuditLog(route.params.auditLogId);
    }

    const initRelationships = () => {
      utenteAppService()
        .retrieve()
        .then(res => {
          utenteApps.value = res.data;
        });
    };

    initRelationships();

    const { t: t$ } = useI18n();
    const validations = useValidation();
    const validationRules = {
      entitaTipo: {},
      entitaId: {},
      azione: {},
      dettagli: {},
      ipAddress: {},
      createdAt: {},
      utente: {},
    };
    const v$ = useVuelidate(validationRules, auditLog as any);
    v$.value.$validate();

    return {
      auditLogService,
      alertService,
      auditLog,
      previousState,
      tipoEntitaValues,
      azioneAuditValues,
      isSaving,
      currentLanguage,
      utenteApps,
      v$,
      ...useDateFormat({ entityRef: auditLog }),
      t$,
    };
  },
  created(): void {},
  methods: {
    save(): void {
      this.isSaving = true;
      if (this.auditLog.id) {
        this.auditLogService()
          .update(this.auditLog)
          .then(param => {
            this.isSaving = false;
            this.previousState();
            this.alertService.showInfo(this.t$('smartbookingApp.auditLog.updated', { param: param.id }));
          })
          .catch(error => {
            this.isSaving = false;
            this.alertService.showHttpError(error.response);
          });
      } else {
        this.auditLogService()
          .create(this.auditLog)
          .then(param => {
            this.isSaving = false;
            this.previousState();
            this.alertService.showSuccess(this.t$('smartbookingApp.auditLog.created', { param: param.id }).toString());
          })
          .catch(error => {
            this.isSaving = false;
            this.alertService.showHttpError(error.response);
          });
      }
    },
  },
});
