import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map, Observable } from 'rxjs';

import { ApiPaginationQueryParams } from '../api-pagination-query-params.interface';
import { ApiPaginatedResponse } from '../api-paginated-response.interface';
import { ApiResponse } from '../api-response.interface';
import { TenantService } from '../tenant.service';
import { Product, ProductDetail } from './catalog.interface';

type HttpParamValue =
  | string
  | number
  | boolean
  | readonly (string | number | boolean)[];

@Injectable({
  providedIn: 'root'
})
export class CatalogService {
  private readonly http = inject(HttpClient);
  private readonly tenantService = inject(TenantService);

  private get tenantApiUrl(): string {
    return this.tenantService.getTenantApiUrl();
  }


  getProductos(
    params?: ApiPaginationQueryParams
  ): Observable<ApiPaginatedResponse<Product[]>> {
    return this.http.get<ApiPaginatedResponse<Product[]>>(
      `${this.tenantApiUrl}/productos`,
      { params: this.buildHttpParams(params) }
    );
  }

  getProducto(id: number, variantId?: number): Observable<ProductDetail> {
    let params = new HttpParams();
    if (variantId) {
      params = params.set('variant_id', variantId);
    }
    
    return this.http
      .get<ApiResponse<ProductDetail>>(`${this.tenantApiUrl}/productos/${id}`, { params })
      .pipe(map((response) => response.data));
  }

  private buildHttpParams(params?: ApiPaginationQueryParams): HttpParams {
    if (!params) {
      return new HttpParams();
    }

    const fromObject = Object.entries(params).reduce<Record<string, HttpParamValue>>(
      (acc, [key, value]) => {
        if (value !== undefined) {
          acc[key] = value;
        }

        return acc;
      },
      {}
    );

    return new HttpParams({ fromObject });
  }
}
