import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, map, of, switchMap, forkJoin } from 'rxjs';
import { environment } from '../../../../environments/environment';
import { PosTerminal } from '../models/pos.model';

@Injectable({ providedIn: 'root' })
export class PosTerminalService {
  private http = inject(HttpClient);
  private base = `${environment.apiUrl}/pos/terminals`;

  list(): Observable<any> {
    return this.http.get<any>(this.base);
  }

  listAll(): Observable<PosTerminal[]> {
    return this.http.get<any>(this.base).pipe(
      switchMap((res) => {
        const data: PosTerminal[] = res.data || [];
        const lastPage = res.meta?.last_page || 1;
        if (lastPage <= 1) return of(data);
        const pages = Array.from({ length: lastPage - 1 }, (_, i) =>
          this.http
            .get<any>(this.base, { params: { page: String(i + 2) } })
            .pipe(map((r) => r.data || []))
        );
        return forkJoin(pages).pipe(map((results) => [...data, ...results.flat()]));
      })
    );
  }

  get(id: number): Observable<PosTerminal> {
    return this.http.get<any>(`${this.base}/${id}`).pipe(map((r) => r.data));
  }

  create(data: any): Observable<PosTerminal> {
    return this.http.post<any>(this.base, data).pipe(map((r) => r.data));
  }

  update(id: number, data: any): Observable<PosTerminal> {
    return this.http.put<any>(`${this.base}/${id}`, data).pipe(map((r) => r.data));
  }

  delete(id: number): Observable<any> {
    return this.http.delete(`${this.base}/${id}`);
  }
}
