import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { Player } from '@interfaces/player';

@Injectable({ providedIn: 'root' })
export class PlayerService {
  private players: Player[] = [
    { id: 1, name: 'Martin', firstName: 'Alex', club: 'Lille Escrime' },
    { id: 2, name: 'Nguyen', firstName: 'Sophie', club: 'Paris Epée' },
    { id: 3, name: 'Klein', firstName: 'Thomas', club: 'Strasbourg Sabre' },
    { id: 4, name: 'Leclerc', firstName: 'Lucie', club: 'Nice Fleuret' },
    { id: 5, name: 'Dubois', firstName: 'Hugo', club: 'Lyon Epée' },
    { id: 6, name: 'Girard', firstName: 'Manon', club: 'Marseille Club' },
  ];

  constructor() {
    console.log('[PlayerService] Initial players loaded:', this.players);
  }

  getPlayers(): Observable<Player[]> {
    console.log('[PlayerService] Fetching all players');
    return of(this.players);
  }

  getPlayerById(id: number): Observable<Player | undefined> {
    const player = this.players.find((p) => p.id === id);
    console.log(`[PlayerService] Fetching player ID: ${id}`, player);
    return of(player);
  }

  getOrCreateByName(
    firstName: string,
    name: string,
    club: string = 'Inconnu'
  ): Observable<Player> {
    const existing = this.players.find(
      (p) =>
        p.firstName.toLowerCase() === firstName.toLowerCase() &&
        p.name.toLowerCase() === name.toLowerCase()
    );

    if (existing) {
      console.log('[PlayerService] Joueur trouvé :', existing);
      return of(existing);
    }

    const newPlayer: Player = {
      id:
        this.players.length > 0
          ? Math.max(...this.players.map((p) => p.id)) + 1
          : 1,
      firstName,
      name,
      club,
    };

    this.players.push(newPlayer);
    console.log('[PlayerService] Nouveau joueur créé :', newPlayer);
    return of(newPlayer);
  }
}
