import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import {
  CommitRecipesResult,
  GeneratedRecipeDraft,
  RecipeGeneratorConstraints,
  RecipeGeneratorSession,
} from '../models/generator.models';

@Injectable({ providedIn: 'root' })
export class RecipeGeneratorService {
  constructor(private readonly http: HttpClient) {}

  createSession(constraints: RecipeGeneratorConstraints): Observable<RecipeGeneratorSession> {
    return this.http.post<RecipeGeneratorSession>('/api/recipe-generator/sessions', constraints);
  }

  fetchSession(id: number): Observable<RecipeGeneratorSession> {
    return this.http.get<RecipeGeneratorSession>(`/api/recipe-generator/sessions/${id}`);
  }

  generateDrafts(sessionId: number, count = 3): Observable<RecipeGeneratorSession> {
    return this.http.post<RecipeGeneratorSession>(`/api/recipe-generator/sessions/${sessionId}/generate`, {
      count,
    });
  }

  regeneratePart(
    sessionId: number,
    draftId: string,
    mode: 'ingredients' | 'steps' | 'full',
    instruction?: string,
  ): Observable<RecipeGeneratorSession> {
    return this.http.post<RecipeGeneratorSession>(`/api/recipe-generator/sessions/${sessionId}/regenerate`, {
      draftId,
      mode,
      instruction,
    });
  }

  removeDraft(sessionId: number, draftId: string): Observable<RecipeGeneratorSession> {
    return this.http.delete<RecipeGeneratorSession>(
      `/api/recipe-generator/sessions/${sessionId}/drafts/${encodeURIComponent(draftId)}`,
    );
  }

  updateDraft(sessionId: number, draft: GeneratedRecipeDraft): Observable<RecipeGeneratorSession> {
    return this.http.put<RecipeGeneratorSession>(`/api/recipe-generator/sessions/${sessionId}/draft`, draft);
  }

  commitRecipes(sessionId: number, draftIds?: string[]): Observable<CommitRecipesResult> {
    return this.http.post<CommitRecipesResult>(`/api/recipe-generator/sessions/${sessionId}/commit`, {
      draftIds: draftIds?.length ? draftIds : undefined,
    });
  }
}
