import { Injectable, inject, signal } from '@angular/core';
import { Player } from '../../models/player.model';
import { TeamsApi } from './teams-api';

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

  private readonly playersSignal = signal<Player[]>([]);
  private readonly loadingSignal = signal(false);
  private readonly loadedForUserId = signal<number | null>(null);

  readonly players = this.playersSignal.asReadonly();
  readonly loading = this.loadingSignal.asReadonly();

  ensureLoaded(userId: number): void {
    if (this.loadedForUserId() === userId || this.loadingSignal()) {
      return;
    }

    this.loadingSignal.set(true);
    this.teamsApi.loadMyTeams(userId).subscribe({
      next: (players) => {
        this.playersSignal.set(players);
        this.loadedForUserId.set(userId);
        this.loadingSignal.set(false);
      },
      error: () => {
        this.loadingSignal.set(false);
      },
    });
  }
}
