import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable, map } from 'rxjs';
import { ApiConfigService } from '../../../core/services/api-config.service';
import { bilingual } from '../../../shared/i18n/bilingual';
import { FinanceSummaryDto, IncomeExpenseDto, BreakdownSliceDto, PieSlice } from '../models/finance-dashboard.model';

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

  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;
  }

  /** All-time balance card (ignores any date range). */
  getSummary(): Observable<FinanceSummaryDto> {
    return this.http.get<FinanceSummaryDto>(`${this.endpoint}/summary`);
  }

  /** Income vs expense totals for the selected date range. */
  getIncomeExpense(from: string, to: string): Observable<IncomeExpenseDto> {
    return this.http.get<IncomeExpenseDto>(`${this.endpoint}/income-expense`, { params: this.toParams({ from, to }) });
  }

  /** Expense breakdown slices for the current drill level; bilingual labels applied here. */
  getBreakdown(from: string, to: string, ministryId?: number | null, categoryGroupId?: number | null): Observable<PieSlice[]> {
    return this.http.get<BreakdownSliceDto[]>(`${this.endpoint}/expense-breakdown`,
      { params: this.toParams({ from, to, ministryId, categoryGroupId }) }).pipe(
        map(list => list.map(s => ({ id: s.id, label: bilingual(s.name_en, s.name_zh), amount: s.amount }))));
  }
}
