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 {
  SalesDeliveryNote,
  CreateSalesDeliveryNote,
  UpdateSalesDeliveryNote,
} from '../models/sales-delivery-note.model';

@Injectable({ providedIn: 'root' })
export class SalesDeliveryNoteService {
  private http = inject(HttpClient);
  private apiUrl = `${environment.apiUrl}/sales/delivery-notes`;

  private buildParams(filters?: Record<string, any>): HttpParams {
    let params = new HttpParams();
    if (filters) {
      Object.entries(filters).forEach(([key, value]) => {
        if (value != null && value !== '') {
          params = params.set(key, String(value));
        }
      });
    }
    return params;
  }

  list(page = 1, perPage = 100, filters?: Record<string, any>): Observable<PaginatedResponse<SalesDeliveryNote>> {
    let params = this.buildParams(filters)
      .set('page', page)
      .set('per_page', perPage);
    return this.http.get<PaginatedResponse<SalesDeliveryNote>>(this.apiUrl, { params });
  }

  /** Fetch ALL pages in parallel and return combined result */
  listAll(): Observable<PaginatedResponse<SalesDeliveryNote>> {
    return this.list(1, 200).pipe(
      switchMap((firstPage) => {
        const lastPage = firstPage.meta.last_page;
        if (lastPage <= 1) {
          return of(firstPage);
        }
        const requests: Observable<PaginatedResponse<SalesDeliveryNote>>[] = [];
        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<SalesDeliveryNote>;
          })
        );
      })
    );
  }

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

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

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

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

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

  ship(id: number, data: { carrier_name: string; tracking_number: string; shipping_method?: string; estimated_delivery?: string }): Observable<ApiResponse<SalesDeliveryNote>> {
    return this.http.post<ApiResponse<SalesDeliveryNote>>(`${this.apiUrl}/${id}/ship`, data);
  }

  deliver(id: number, data: { delivered_at: string; received_by?: string }): Observable<ApiResponse<SalesDeliveryNote>> {
    return this.http.post<ApiResponse<SalesDeliveryNote>>(`${this.apiUrl}/${id}/deliver`, data);
  }

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

  getPdf(id: number): Observable<Blob> {
    return this.http.get(`${this.apiUrl}/${id}/pdf`, { responseType: 'blob' });
  }
}
