import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ApiConfigService } from '../../../core/services/api-config.service';
import {
  OfferingSessionDto, OfferingSessionListItemDto,
  CreateOfferingSessionRequest, PagedResult,
} from '../models/giving.model';

@Injectable({ providedIn: 'root' })
export class OfferingSessionApiService {
  private readonly endpoint: string;
  constructor(private http: HttpClient, apiConfig: ApiConfigService) {
    this.endpoint = apiConfig.getApiUrl('offering-sessions');
  }

  getPaged(page = 1, pageSize = 20, from?: string, to?: string): Observable<PagedResult<OfferingSessionListItemDto>> {
    let params = new HttpParams().set('page', page).set('pageSize', pageSize);
    if (from) params = params.set('from', from);
    if (to) params = params.set('to', to);
    return this.http.get<PagedResult<OfferingSessionListItemDto>>(this.endpoint, { params });
  }
  getById(id: number): Observable<OfferingSessionDto> {
    return this.http.get<OfferingSessionDto>(`${this.endpoint}/${id}`);
  }
  checkDate(date: string): Observable<{ exists: boolean }> {
    const params = new HttpParams().set('date', date);
    return this.http.get<{ exists: boolean }>(`${this.endpoint}/check-date`, { params });
  }
  create(request: CreateOfferingSessionRequest): Observable<{ id: number }> {
    return this.http.post<{ id: number }>(this.endpoint, request);
  }
  reopen(id: number): Observable<void> {
    return this.http.post<void>(`${this.endpoint}/${id}/reopen`, {});
  }
  replace(id: number, request: CreateOfferingSessionRequest): Observable<void> {
    return this.http.put<void>(`${this.endpoint}/${id}`, request);
  }

  /** Upload the merged paper-proof PDF (built client-side) for a session. */
  uploadProof(id: number, pdf: Blob): Observable<void> {
    const form = new FormData();
    form.append('file', pdf, 'proof.pdf');
    return this.http.post<void>(`${this.endpoint}/${id}/proof`, form);
  }

  /**
   * Fetch the proof PDF as a Blob via HttpClient so the auth interceptor attaches the JWT.
   * A bare window.open on the API URL would be an unauthenticated navigation → 401.
   */
  downloadProof(id: number): Observable<Blob> {
    return this.http.get(`${this.endpoint}/${id}/proof`, { responseType: 'blob' });
  }

  deleteProof(id: number): Observable<void> {
    return this.http.delete<void>(`${this.endpoint}/${id}/proof`);
  }
}
