import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ApiService } from './api.service';
import { AuthService } from './auth.service';

// Interfaccia per i dati del bambino
export interface Child {
  id: number;
  first_name: string;
  last_name: string;
  date_of_birth: string; // YYYY-MM-DD
  enrollment_date: string; // YYYY-MM-DD
  structure_id?: number | null;
  parent1_name?: string | null;
  parent1_phone?: string | null;
  parent1_email?: string | null;
  parent2_name?: string | null;
  parent2_phone?: string | null;
  parent2_email?: string | null;
  address?: string | null;
  city?: string | null;
  notes?: string | null;
  is_active: boolean; // O number
  created_at: string;
  updated_at: string;
  // Campi joinati (se presenti, come structure_name)
  structure_name?: string | null;
}

// Interfaccia per i dati di input
export type ChildInput = Partial<Omit<Child, 'id' | 'created_at' | 'updated_at' | 'structure_name'>>;

@Injectable({
  providedIn: 'root'
})
export class ChildService extends ApiService {

  constructor(authService: AuthService, http: HttpClient) {
    super(authService, http, 'children');
  }

  // GET /api/children (con filtri opzionali)
  getChildren(filters: { structure_id?: number, is_active?: boolean } = {}): Observable<Child[]> {
    let params = new HttpParams();
    if (filters.structure_id !== undefined && filters.structure_id !== null) {
      params = params.set('structure_id', filters.structure_id.toString());
    }
    if (filters.is_active !== undefined && filters.is_active !== null) {
      params = params.set('is_active', filters.is_active.toString()); // Invia 'true' o 'false' come stringa
    }

    return this.get<Child[]>(`${this.controllerName}`, params);
    // Il backend restituisce già dati parziali per la lista
    //return this.http.get<Child[]>(this.apiUrl, { params });
  }

  // GET /api/children/{id}
  getChild(id: number): Observable<Child> {
    return this.get<Child>(`${this.controllerName}/${id}`); // Recupera dati completi
  }

  // POST /api/children
  addChild(child: ChildInput): Observable<Child> {
    // Invia come JSON
    return this.post<Child>(`${this.controllerName}`, child);
  }

  // PUT /api/children/{id}
  updateChild(id: number, child: ChildInput): Observable<Child> {
    // Invia come JSON
    return this.put<Child>(`${this.controllerName}/${id}`, child);
  }

  // DELETE /api/children/{id}
  deleteChild(id: number): Observable<null> {
    return this.delete<null>(`${this.controllerName}/${id}`);
  }
}
