import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError, Observable } from 'rxjs';
import { BlackjackGame } from '@blackjack/models/blackjack.model';

@Injectable({
  providedIn: 'root',
})
export class BlackjackService {
  private http = inject(HttpClient);

  startGame(bet: number): Observable<BlackjackGame> {
    return this.http
      .post<BlackjackGame>('/backend/blackjack/start', { betAmount: bet }, { responseType: 'json' })
      .pipe(
        catchError((error) => {
          console.error('Start game error:', error);
          throw error;
        })
      );
  }

  hit(gameId: number): Observable<BlackjackGame> {
    return this.http
      .post<BlackjackGame>(`/backend/blackjack/${gameId}/hit`, {}, { responseType: 'json' })
      .pipe(
        catchError((error) => {
          console.error('Hit error:', error);
          throw error;
        })
      );
  }

  stand(gameId: number): Observable<BlackjackGame> {
    return this.http
      .post<BlackjackGame>(`/backend/blackjack/${gameId}/stand`, {}, { responseType: 'json' })
      .pipe(
        catchError((error) => {
          console.error('Stand error:', error);
          throw error;
        })
      );
  }

  doubleDown(gameId: number): Observable<BlackjackGame> {
    return this.http
      .post<BlackjackGame>(`/backend/blackjack/${gameId}/doubleDown`, {}, { responseType: 'json' })
      .pipe(
        catchError((error) => {
          console.error('Double Down error:', error);
          throw error;
        })
      );
  }

  getGame(gameId: number): Observable<BlackjackGame> {
    return this.http
      .get<BlackjackGame>(`/backend/blackjack/${gameId}`, { responseType: 'json' })
      .pipe(
        catchError((error) => {
          console.error('Get game error:', error);
          throw error;
        })
      );
  }
}
