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

import { TENANT_CURRENCIES_ENDPOINTS } from './tenant-currencies.endpoints';
import { DataTableQuery, DataTableResult } from '../../../shared/components/data-table/data-table.types';
import {
  CreateTenantCurrencyRequest,
  TenantCurrencyDto,
  TenantCurrencyDto as TenantCurrencyDtoAlias,
  TenantCurrencyLookupDto,
  UpdateTenantCurrencyRequest
} from '../models/tenant-currencies.model';

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

    getTenantDataTable(query: DataTableQuery): Observable<DataTableResult<TenantCurrencyDto>> {
        return this.http.post<DataTableResult<TenantCurrencyDto>>(TENANT_CURRENCIES_ENDPOINTS.dataTable, query);
    }

    createTenant(request: CreateTenantCurrencyRequest): Observable<TenantCurrencyDto> {
        return this.http.post<TenantCurrencyDto>(TENANT_CURRENCIES_ENDPOINTS.create, request);
    }

    updateTenant(id: string, request: UpdateTenantCurrencyRequest): Observable<TenantCurrencyDto> {
        return this.http.put<TenantCurrencyDto>(TENANT_CURRENCIES_ENDPOINTS.update(id), request);
    }

    getTenantById(id: string): Observable<TenantCurrencyDto> {
        return this.http.get<TenantCurrencyDto>(TENANT_CURRENCIES_ENDPOINTS.getById(id));
    }

    autocomplete(term?: string, limit = 10): Observable<readonly TenantCurrencyLookupDto[]> {
        let params = new HttpParams().set('limit', limit);
        const normalizedTerm = term?.trim();

        if (normalizedTerm) {
            params = params.set('term', normalizedTerm);
        }

        return this.http.get<readonly TenantCurrencyLookupDto[]>(TENANT_CURRENCIES_ENDPOINTS.autocomplete, { params });
    }
}
