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 { Warehouse, CreateWarehouse, UpdateWarehouse } from '../models/warehouse.model';
import { BranchContextService } from './branch-context.service';

@Injectable({ providedIn: 'root' })
export class WarehouseService {
  private http = inject(HttpClient);
  private branchContext = inject(BranchContextService);
  private apiUrl = `${environment.apiUrl}/inventory/warehouses`;

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

  listAll(): Observable<PaginatedResponse<Warehouse>> {
    return this.list(1, 200).pipe(
      switchMap((firstPage) => {
        const lastPage = firstPage.meta.last_page;
        if (lastPage <= 1) return of(firstPage);
        const requests: Observable<PaginatedResponse<Warehouse>>[] = [];
        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<Warehouse>;
          })
        );
      })
    );
  }

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

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

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

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

  /** List all active warehouses filtered by user's branch access */
  listForCurrentBranch(): Observable<PaginatedResponse<Warehouse>> {
    return this.listAll().pipe(
      map(res => ({
        ...res,
        data: res.data.filter(w => w.is_active && this.branchContext.isWarehouseAllowed(w.branch_id)),
      }))
    );
  }
}
