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

@Injectable({ providedIn: 'root' })
export class HrJobOpeningService {
  private http = inject(HttpClient);
  private apiUrl = `${environment.apiUrl}/hr/job-openings`;

  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<any>> {
    const params = this.buildParams(filters).set('page', page).set('per_page', perPage);
    return this.http.get<PaginatedResponse<any>>(this.apiUrl, { params });
  }

  listAll(filters?: Record<string, any>): Observable<PaginatedResponse<any>> {
    return this.list(1, 200, filters).pipe(
      switchMap((firstPage) => {
        const lastPage = firstPage.meta?.last_page ?? 1;
        if (lastPage <= 1) return of(firstPage);
        const requests: Observable<PaginatedResponse<any>>[] = [];
        for (let p = 2; p <= lastPage; p++) {
          requests.push(this.list(p, 200, filters));
        }
        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<any>;
          })
        );
      })
    );
  }

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

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

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

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