import { inject, Injectable, signal } from '@angular/core';
import { GetCurrentLocationUseCase } from '../../application/location/get-current-location.use-case';
import { Coordinates } from '@app/domain/localisation/coordinates.model';

export interface LocationState {
  coordinates: Coordinates | null;
  isLocationEnabled: boolean;
  isLoading: boolean;
  error: string | null;
}

@Injectable()
export class LocationFacade {
  private readonly getCurrentLocationUseCase = inject(GetCurrentLocationUseCase);

  readonly locationState = signal<LocationState>({
    coordinates: null,
    isLocationEnabled: false,
    isLoading: false,
    error: null,
  });

  getCurrentLocation(): void {
    this.setLoading(true);
    this.clearError();

    this.getCurrentLocationUseCase.execute().subscribe({
      next: (coordinates) => {
        this.updateState({ coordinates });
        this.setLoading(false);
      },
      error: (error) => {
        this.setError(error.message || 'Erreur lors de la récupération de la position');
        this.setLoading(false);
      },
    });
  }

  private updateState(partial: Partial<LocationState>): void {
    this.locationState.update((state) => ({ ...state, ...partial }));
  }

  private setLoading(isLoading: boolean): void {
    this.updateState({ isLoading });
  }

  private setError(error: string): void {
    this.updateState({ error });
  }

  private clearError(): void {
    this.updateState({ error: null });
  }
}
