import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { Referee, RefereeLevel } from '@interfaces/referee';

@Injectable({ providedIn: 'root' })
export class RefereeService {
  private referees: Referee[] = [
    {
      id: 10,
      name: 'Durand',
      firstName: 'Pierre',
      level: RefereeLevel.NATIONAL,
    },
    {
      id: 11,
      name: 'Lemoine',
      firstName: 'Anna',
      level: RefereeLevel.REGIONAL,
    },
    {
      id: 12,
      name: 'Morel',
      firstName: 'Lucas',
      level: RefereeLevel.DEPARTMENTAL,
    },
  ];

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

  getReferees(): Observable<Referee[]> {
    console.log('[RefereeService] Fetching all referees');
    return of(this.referees);
  }

  getRefereeById(id: number): Observable<Referee | undefined> {
    const ref = this.referees.find((r) => r.id === id);
    console.log(`[RefereeService] Fetching referee ID: ${id}`, ref);
    return of(ref);
  }

  getOrCreateByName(
    firstName: string,
    name: string,
    level: RefereeLevel
  ): Observable<Referee> {
    const existing = this.referees.find(
      (r) =>
        r.firstName.toLowerCase() === firstName.toLowerCase() &&
        r.name.toLowerCase() === name.toLowerCase()
    );

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

    const newPlayer: Referee = {
      id:
        this.referees.length > 0
          ? Math.max(...this.referees.map((r) => r.id)) + 1
          : 1,
      firstName,
      name,
      level,
    };

    this.referees.push(newPlayer);
    console.log('[RefereeService] Nouveau arbitre créé :', newPlayer);
    return of(newPlayer);
  }
}
