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 {
  GivingListItemDto, CreateGivingRequest, UpdateGivingRequest, PagedResult,
} from '../models/giving.model';

export interface GivingQuery {
  page?: number; pageSize?: number; search?: string;
  categoryId?: number; from?: string; to?: string;
}

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

  getPaged(q: GivingQuery = {}): Observable<PagedResult<GivingListItemDto>> {
    let p = new HttpParams().set('page', q.page ?? 1).set('pageSize', q.pageSize ?? 20);
    if (q.search)            p = p.set('search', q.search);
    if (q.categoryId != null) p = p.set('categoryId', q.categoryId);
    if (q.from)              p = p.set('from', q.from);
    if (q.to)                p = p.set('to', q.to);
    return this.http.get<PagedResult<GivingListItemDto>>(this.endpoint, { params: p });
  }
  create(request: CreateGivingRequest): Observable<{ id: number }> {
    return this.http.post<{ id: number }>(this.endpoint, request);
  }
  update(id: number, request: UpdateGivingRequest): Observable<void> {
    return this.http.put<void>(`${this.endpoint}/${id}`, request);
  }
  delete(id: number): Observable<void> {
    return this.http.delete<void>(`${this.endpoint}/${id}`);
  }
}
