import { Injectable, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { EMPTY, Subject } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';
import { Team } from '../../models/team.model';
import { TeamsApi } from './teams-api';

@Injectable({ providedIn: 'root' })
export class TeamStore {
  private readonly teamsApi = inject(TeamsApi);

  private readonly teamSignal = signal<Team | null>(null);
  private readonly loadingSignal = signal(false);
  private readonly requestedTeamId = signal<number | null>(null);
  private readonly requests = new Subject<number>();

  readonly team = this.teamSignal.asReadonly();
  readonly loading = this.loadingSignal.asReadonly();

  constructor() {
    this.requests
      .pipe(
        switchMap((teamId) =>
          this.teamsApi.loadTeamOverview(teamId).pipe(
            catchError(() => {
              this.requestedTeamId.set(null);
              this.loadingSignal.set(false);
              return EMPTY;
            }),
          ),
        ),
        takeUntilDestroyed(),
      )
      .subscribe((team) => {
        this.teamSignal.set(team);
        this.loadingSignal.set(false);
      });
  }

  loadTeam(teamId: number): void {
    if (this.requestedTeamId() === teamId) {
      return;
    }

    this.requestedTeamId.set(teamId);
    this.loadingSignal.set(true);
    this.requests.next(teamId);
  }

  refreshTeam(): void {
    const teamId = this.requestedTeamId();
    if (teamId === null) return;
    this.loadingSignal.set(true);
    this.requests.next(teamId);
  }
}
