import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AdminReview, AdminReviewListFilters, AdminReviewsListResult, AdminReviewStatus } from '../models/admin-review.model';
import { AdminReport, AdminReportStatus } from '../models/admin-report.model';
import { AdminModerationGateway } from './admin-moderation-gateway.interface';

/**
 * No dedicated moderation contract doc exists yet - at the conventional
 * /api/admin/v2/{resource} path used throughout the rest of docs/backend/.
 */
@Injectable({ providedIn: 'root' })
export class AdminModerationApiGateway implements AdminModerationGateway {
  private readonly http = inject(HttpClient);

  loadReviews(filters: AdminReviewListFilters): Observable<AdminReviewsListResult> {
    let params = new HttpParams();
    for (const [key, value] of Object.entries(filters ?? {})) {
      if (value !== undefined && value !== null && value !== '') {
        params = params.set(key, String(value));
      }
    }
    return this.http.get<AdminReviewsListResult>('/api/admin/v2/moderation/reviews', { params });
  }

  loadReview(id: string): Observable<AdminReview | null> {
    return this.http.get<AdminReview | null>(`/api/admin/v2/moderation/reviews/${encodeURIComponent(id)}`);
  }

  setReviewStatus(id: string, status: AdminReviewStatus, note: string): Observable<AdminReview | null> {
    return this.http.patch<AdminReview | null>(`/api/admin/v2/moderation/reviews/${encodeURIComponent(id)}`, { status, note });
  }

  setReviewVisible(id: string, visible: boolean): Observable<AdminReview | null> {
    return this.http.patch<AdminReview | null>(`/api/admin/v2/moderation/reviews/${encodeURIComponent(id)}`, { visible });
  }

  setReviewPinned(id: string, pinned: boolean): Observable<AdminReview | null> {
    return this.http.patch<AdminReview | null>(`/api/admin/v2/moderation/reviews/${encodeURIComponent(id)}`, { pinned });
  }

  setReviewFeatured(id: string, featured: boolean): Observable<AdminReview | null> {
    return this.http.patch<AdminReview | null>(`/api/admin/v2/moderation/reviews/${encodeURIComponent(id)}`, { featured });
  }

  addModeratorNote(id: string, note: string): Observable<AdminReview | null> {
    return this.http.post<AdminReview | null>(`/api/admin/v2/moderation/reviews/${encodeURIComponent(id)}/notes`, { note });
  }

  deleteReview(id: string): Observable<void> {
    return this.http
      .delete(`/api/admin/v2/moderation/reviews/${encodeURIComponent(id)}`)
      .pipe(map(() => undefined));
  }

  loadReports(): Observable<AdminReport[]> {
    return this.http.get<AdminReport[]>('/api/admin/v2/moderation/reports');
  }

  setReportStatus(id: string, status: AdminReportStatus): Observable<AdminReport | null> {
    return this.http.patch<AdminReport | null>(`/api/admin/v2/moderation/reports/${encodeURIComponent(id)}`, { status });
  }
}
