import { Injectable, inject } from "@angular/core";
import { firstValueFrom } from "rxjs";
import type {
  Suggestion,
  SuggestionStatus,
  SuggestionEntity,
  CreateSuggestionDto,
  DeclineSuggestionDto,
} from "@library/shared-types";
import { ApiService } from "./api.service";

@Injectable({
  providedIn: "root",
})
export class SuggestionService {
  private api = inject(ApiService);

  async getAllSuggestions(filters?: {
    status?: SuggestionStatus;
    entityType?: SuggestionEntity;
  }): Promise<Suggestion[]> {
    const params = new URLSearchParams();
    if (filters?.status) {
      params.set("status", filters.status);
    }
    if (filters?.entityType) {
      params.set("entityType", filters.entityType);
    }

    const queryString = params.toString();
    const url = queryString ? `/suggestions?${queryString}` : "/suggestions";

    return firstValueFrom(this.api.get<Suggestion[]>(url));
  }

  async getMySuggestions(): Promise<Suggestion[]> {
    return firstValueFrom(this.api.get<Suggestion[]>("/suggestions/my"));
  }

  async getSuggestionById(id: string): Promise<Suggestion> {
    return firstValueFrom(this.api.get<Suggestion>(`/suggestions/${id}`));
  }

  async createSuggestion(data: CreateSuggestionDto): Promise<Suggestion> {
    return firstValueFrom(this.api.post<Suggestion>("/suggestions", data));
  }

  async acceptSuggestion(id: string): Promise<Suggestion> {
    return firstValueFrom(this.api.put<Suggestion>(`/suggestions/${id}/accept`, {}));
  }

  async acceptSuggestionWithEdits(id: string, data: any): Promise<Suggestion> {
    return firstValueFrom(this.api.put<Suggestion>(`/suggestions/${id}/accept-with-edits`, data));
  }

  async declineSuggestion(id: string, data: DeclineSuggestionDto): Promise<Suggestion> {
    return firstValueFrom(this.api.put<Suggestion>(`/suggestions/${id}/decline`, data));
  }
}
