import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable, forkJoin, of } from 'rxjs';
import { switchMap, map } from 'rxjs/operators';
import { environment } from '../../../environments/environment';
import { ApiResponse, PaginatedResponse } from '../models/api.model';
import { CheckIssued, CreateCheckIssued, UpdateCheckIssued } from '../models/check-issued.model';

@Injectable({ providedIn: 'root' })
export class CheckIssuedService {
  private http = inject(HttpClient);
  private apiUrl = `${environment.apiUrl}/accounting/checks-issued`;

  list(page = 1, perPage = 100): Observable<PaginatedResponse<CheckIssued>> {
    const params = new HttpParams().set('page', page).set('per_page', perPage);
    return this.http.get<PaginatedResponse<CheckIssued>>(this.apiUrl, { params });
  }

  listAll(): Observable<PaginatedResponse<CheckIssued>> {
    return this.list(1, 200).pipe(
      switchMap((firstPage) => {
        const lastPage = firstPage.meta.last_page;
        if (lastPage <= 1) return of(firstPage);
        const requests: Observable<PaginatedResponse<CheckIssued>>[] = [];
        for (let p = 2; p <= lastPage; p++) requests.push(this.list(p, 200));
        return forkJoin(requests).pipe(
          map((responses) => {
            const allData = [...firstPage.data, ...responses.flatMap((r) => r.data)];
            return { data: allData, links: firstPage.links, meta: { ...firstPage.meta, current_page: 1, last_page: 1, per_page: allData.length, to: allData.length, total: allData.length } } as PaginatedResponse<CheckIssued>;
          })
        );
      })
    );
  }

  getById(id: number): Observable<ApiResponse<CheckIssued>> {
    return this.http.get<ApiResponse<CheckIssued>>(`${this.apiUrl}/${id}`);
  }

  create(data: CreateCheckIssued): Observable<ApiResponse<CheckIssued>> {
    return this.http.post<ApiResponse<CheckIssued>>(this.apiUrl, data);
  }

  update(id: number, data: UpdateCheckIssued): Observable<ApiResponse<CheckIssued>> {
    return this.http.put<ApiResponse<CheckIssued>>(`${this.apiUrl}/${id}`, data);
  }

  delete(id: number): Observable<{ message: string }> {
    return this.http.delete<{ message: string }>(`${this.apiUrl}/${id}`);
  }

  deliver(id: number): Observable<ApiResponse<CheckIssued>> {
    return this.http.post<ApiResponse<CheckIssued>>(`${this.apiUrl}/${id}/deliver`, {});
  }

  cash(id: number): Observable<ApiResponse<CheckIssued>> {
    return this.http.post<ApiResponse<CheckIssued>>(`${this.apiUrl}/${id}/cash`, {});
  }

  cancel(id: number): Observable<ApiResponse<CheckIssued>> {
    return this.http.post<ApiResponse<CheckIssued>>(`${this.apiUrl}/${id}/cancel`, {});
  }
}
