import { Injectable, DestroyRef, inject } from '@angular/core';
import { Router } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { GameApiService } from './game-api.service';
import { getErrorMessage } from '../core/http/error-message.util';

@Injectable({ providedIn: 'root' })
export class GameImportService {
  private readonly gameApi = inject(GameApiService);
  private readonly router = inject(Router);
  private readonly destroyRef = inject(DestroyRef);

  importFen(
    fen: string,
    onSuccess: () => void,
    onError: (error: string) => void
  ): void {
    const trimmedFen = fen.trim();
    if (!trimmedFen) {
      onError('Please provide a FEN string.');
      return;
    }

    this.gameApi
      .importFen(trimmedFen)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (game) => {
          onSuccess();
          void this.router.navigate(['/game', game.gameId]);
        },
        error: (error) => {
          onError(getErrorMessage(error, 'FEN import failed.'));
        }
      });
  }

  importPgn(
    pgn: string,
    onSuccess: () => void,
    onError: (error: string) => void
  ): void {
    const trimmedPgn = pgn.trim();
    if (!trimmedPgn) {
      onError('Please provide a PGN string.');
      return;
    }

    this.gameApi
      .importPgn(trimmedPgn)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe({
        next: (game) => {
          onSuccess();
          void this.router.navigate(['/game', game.gameId]);
        },
        error: (error) => {
          onError(getErrorMessage(error, 'PGN import failed.'));
        }
      });
  }
}
