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 {
  PagedResult, PayeeGroupDto, IssueChecksRequest, IssueChecksResultDto,
  CheckListItemDto, CheckDetailDto, ChurchProfileDto, UpdateChurchProfileRequest,
} from '../models/disbursement.model';

export interface CheckRegisterQuery {
  page?: number; pageSize?: number; status?: string; search?: string; from?: string; to?: string;
}

@Injectable({ providedIn: 'root' })
export class DisbursementApiService {
  private readonly endpoint: string;
  private readonly profileEndpoint: string;

  constructor(private http: HttpClient, apiConfig: ApiConfigService) {
    this.endpoint = apiConfig.getApiUrl('disbursements');
    this.profileEndpoint = apiConfig.getApiUrl('church-profile');
  }

  private toParams(q: Record<string, unknown>): HttpParams {
    let p = new HttpParams();
    for (const [k, v] of Object.entries(q)) if (v !== undefined && v !== null && v !== '') p = p.set(k, String(v));
    return p;
  }

  getApprovedUnpaid(): Observable<PayeeGroupDto[]> {
    return this.http.get<PayeeGroupDto[]>(`${this.endpoint}/approved-unpaid`);
  }

  issue(req: IssueChecksRequest): Observable<IssueChecksResultDto> {
    return this.http.post<IssueChecksResultDto>(`${this.endpoint}/issue`, req);
  }

  getRegister(q: CheckRegisterQuery): Observable<PagedResult<CheckListItemDto>> {
    return this.http.get<PagedResult<CheckListItemDto>>(`${this.endpoint}/checks`, { params: this.toParams(q as Record<string, unknown>) });
  }

  getCheck(id: number): Observable<CheckDetailDto> {
    return this.http.get<CheckDetailDto>(`${this.endpoint}/checks/${id}`);
  }

  voidCheck(id: number, reason: string | null): Observable<void> {
    return this.http.post<void>(`${this.endpoint}/checks/${id}/void`, { reason });
  }

  /** Blob fetch via HttpClient so the auth interceptor attaches the JWT (a raw window.open would 401). */
  downloadCheckPdf(id: number): Observable<Blob> {
    return this.http.get(`${this.endpoint}/checks/${id}/pdf`, { responseType: 'blob' });
  }

  /** Signed receipt PDF (check info + disbursement detail + e-signature). */
  downloadReceiptPdf(id: number): Observable<Blob> {
    return this.http.get(`${this.endpoint}/checks/${id}/receipt-pdf`, { responseType: 'blob' });
  }

  acknowledge(id: number, signature: Blob, signedName: string): Observable<void> {
    const form = new FormData();
    form.append('signature', signature, `check-${id}-signature.png`);
    form.append('signedName', signedName);
    return this.http.post<void>(`${this.endpoint}/checks/${id}/acknowledge`, form);
  }

  getSignature(id: number): Observable<Blob> {
    return this.http.get(`${this.endpoint}/checks/${id}/signature`, { responseType: 'blob' });
  }

  getChurchProfile(): Observable<ChurchProfileDto> {
    return this.http.get<ChurchProfileDto>(this.profileEndpoint);
  }

  updateChurchProfile(r: UpdateChurchProfileRequest): Observable<void> {
    return this.http.put<void>(this.profileEndpoint, r);
  }
}
