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 { AttendanceCounts } from '../models/attendance.model';

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

  constructor(private http: HttpClient, apiConfig: ApiConfigService) {
    this.endpoint = apiConfig.getApiUrl('meal-attendance');
  }

  /** Today's live counts (public; SignalR-independent fallback). */
  getToday(): Observable<AttendanceCounts> {
    return this.http.get<AttendanceCounts>(`${this.endpoint}/today`);
  }

  /** Daily counts within an inclusive yyyy-MM-dd range, for the dashboard chart. */
  getRange(from: string, to: string): Observable<AttendanceCounts[]> {
    const params = new HttpParams().set('from', from).set('to', to);
    return this.http.get<AttendanceCounts[]>(this.endpoint, { params });
  }

  /** Overwrite a specific Sunday's counts (back-office editor). */
  setCounts(date: string, counts: { adult: number; youth: number; kid: number }): Observable<AttendanceCounts> {
    return this.http.put<AttendanceCounts>(`${this.endpoint}/${date}`, counts);
  }
}
