import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { Matches, MatchState } from '@interfaces/matches';

@Injectable({ providedIn: 'root' })
export class MatchesService {
  private matches: Matches[] = [
    {
      id: 1,
      refereeID: 10,
      player1ID: 1,
      score1: 15,
      player2ID: 2,
      score2: 13,
      country: 'France',
      city: 'Paris',
      weapon: 'Fleuret',
      date: new Date('2025-06-10T14:00:00'),
      state: MatchState.OVER,
    },
    {
      id: 2,
      refereeID: 11,
      player1ID: 3,
      score1: 5,
      player2ID: 4,
      score2: 7,
      country: 'France',
      city: 'Lyon',
      weapon: 'Épée',
      date: new Date('2025-06-15T10:00:00'),
      state: MatchState.ONGOING,
    },
    {
      id: 3,
      refereeID: 12,
      player1ID: 5,
      score1: 0,
      player2ID: 6,
      score2: 0,
      country: 'Belgique',
      city: 'Bruxelles',
      weapon: 'Sabre',
      date: new Date('2025-06-20T16:30:00'),
      state: MatchState.NOT_STARTED,
    },
  ];
  private nextMatchId = Math.max(...this.matches.map((m) => m.id)) + 1;

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

  getMatches(): Observable<Matches[]> {
    console.log('[MatchesService] Fetching all matches');
    return of(this.matches);
  }

  getMatchById(id: number): Observable<Matches | undefined> {
    const match = this.matches.find((m) => m.id === id);
    console.log(`[MatchesService] Fetching match ID: ${id}`, match);
    return of(match);
  }

  // Préparation future pour WebSocket
  connectToMatchUpdatesWebSocket(): void {
    console.log(
      '[MatchesService] WebSocket connection placeholder initialized'
    );
    // ici tu pourrais plus tard faire : this.socket = new WebSocket('ws://...') etc.
  }

  updateMatch(id: number, updatedData: Partial<Matches>): void {
    const match = this.matches.find((m) => m.id === id);
    if (match) {
      Object.assign(match, updatedData);
      console.log(`[MatchesService] Match ${id} mis à jour :`, match);
    } else {
      console.warn(`[MatchesService] Match ${id} introuvable`);
    }
  }

  create(match: Omit<Matches, 'id'>): Observable<Matches> {
    const newMatch: Matches = {
      ...match,
      id: this.nextMatchId++,
    };

    this.matches.push(newMatch);
    console.log('[MatchesService] Match created:', newMatch);
    return of(newMatch);
  }

  deleteMatch(id: number): Observable<boolean> {
    const index = this.matches.findIndex((m) => m.id === id);

    if (index !== -1) {
      const deletedMatch = this.matches.splice(index, 1)[0];
      console.log(`[MatchesService] Match ${id} supprimé :`, deletedMatch);

      return of(true);
    } else {
      console.warn(`[MatchesService] Match ${id} introuvable pour suppression`);
      return of(false);
    }
  }
}
