import { HttpClient } from '@angular/common/http';
import { inject, Injectable, InjectionToken } from '@angular/core';
import {
  ChoosePerkRequest,
  ChoosePerkRequestSchema,
  MissionStateResponse,
  MissionStateResponseSchema,
  StartMissionRequest,
  StartMissionRequestSchema,
  SurvivorSchema,
} from '@fog-explorer/api-interfaces';
import { map, Observable } from 'rxjs';

export const EBS_BASE_URL = new InjectionToken<string>('EBS_BASE_URL');

@Injectable({ providedIn: 'root' })
export class EbsApiService {
  private readonly http = inject(HttpClient);
  private readonly baseUrl = inject(EBS_BASE_URL, { optional: true }) ?? 'https://localhost:3000';

  getMissionState(): Observable<MissionStateResponse> {
    return this.http
      .get(`${this.baseUrl}/missions/state`)
      .pipe(map((body) => MissionStateResponseSchema.parse(body)));
  }

  startMission(req: StartMissionRequest): Observable<NonNullable<MissionStateResponse>> {
    StartMissionRequestSchema.parse(req);
    return this.http
      .post(`${this.baseUrl}/missions/start`, req)
      .pipe(
        map((body) => {
          const parsed = MissionStateResponseSchema.parse(body);
          if (!parsed) throw new Error('Unexpected null from /missions/start');
          return parsed;
        }),
      );
  }

  abandonMission(): Observable<void> {
    return this.http.post<void>(`${this.baseUrl}/missions/abandon`, {});
  }

  choosePerk(req: ChoosePerkRequest) {
    ChoosePerkRequestSchema.parse(req);
    return this.http
      .post(`${this.baseUrl}/missions/choose-perk`, req)
      .pipe(map((body) => SurvivorSchema.parse(body)));
  }
}
