// aviso-resolver.service.ts
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable, forkJoin, of } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';
import { AvisoService, AvisoArrivalsResponse } from '../../services/aviso.service';
import { AvisoTvTextSettingsDto, TvSettings } from '../../services/aviso.dto';

interface AvisoResolvedData {
  standortID?: number;
  avisoTvTextSettings: AvisoTvTextSettingsDto[];
  avisoTvSettings: TvSettings[];
  arrivals: AvisoArrivalsResponse;
}

@Injectable({
  providedIn: 'root',
})
export class AvisoResolver implements Resolve<AvisoResolvedData> {
  constructor(private avisoService: AvisoService) { }

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<AvisoResolvedData> {
    const standort = route.queryParamMap.get('standort') || '';
    const onlyOK = route.queryParamMap.get('onlyOK') === 'true';

    if (!standort) {
      console.error('Standort-Parameter fehlt.');
      return of({
        avisoTvTextSettings: [],
        avisoTvSettings: [],
        arrivals: { avisos: [], totalCount: 0 }
      } as AvisoResolvedData);
    }

    return this.avisoService.getStandortID(standort).pipe(
      catchError(error => {
        console.error('Fehler beim Abrufen der StandortID', error);
        return of(null);
      }),
      switchMap(result => {
        if (!result || !result.standortID) {
          console.error('StandortID konnte nicht abgerufen werden.');
          return of({
            avisoTvTextSettings: [],
            avisoTvSettings: [],
            arrivals: { avisos: [], totalCount: 0 }
          } as AvisoResolvedData);
        }

        const standortID = result.standortID;

        return forkJoin({
          avisoTvTextSettings: this.avisoService.getAvisoTvTextSettings(standort).pipe(
            catchError(error => {
              console.error('Fehler beim Laden der TV Text Settings', error);
              return of([] as AvisoTvTextSettingsDto[]);
            })
          ),
          avisoTvSettings: this.avisoService.getAvisoTvSettings(standortID).pipe(
            catchError(error => {
              console.error('Fehler beim Laden der TV Settings', error);
              return of([] as TvSettings[]);
            })
          ),
          arrivals: this.avisoService.getArrivals(standort, onlyOK).pipe(
            catchError(error => {
              console.error('Fehler beim Laden der Arrivals', error);
              return of({ avisos: [], totalCount: 0 } as AvisoArrivalsResponse);
            })
          )
        }).pipe(
           switchMap(data => {
            return of({
              standortID,
              avisoTvTextSettings: data.avisoTvTextSettings,
              avisoTvSettings: data.avisoTvSettings,
              arrivals: data.arrivals
            } as AvisoResolvedData);
          })
        );
      }),
      catchError(error => {
        console.error('Allgemeiner Fehler im Resolver', error);
        return of({
          avisoTvTextSettings: [],
          avisoTvSettings: [],
          arrivals: { avisos: [], totalCount: 0 }
        } as AvisoResolvedData);
      })
    );
  }
}
