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

import { DataTableQuery, DataTableResult } from '../../../../shared/components/data-table/data-table.types';
import {
    CreateCurrencyRequest,
    CurrencyDto,
    CurrencyLookupDto,
    UpdateCurrencyRequest
} from '../models/currency.model';
import { CURRENCY_ENDPOINTS } from './currency.endpoints';

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

    getCurrencyDataTable(query: DataTableQuery): Observable<DataTableResult<CurrencyDto>> {
        return this.http.post<DataTableResult<CurrencyDto>>(CURRENCY_ENDPOINTS.dataTable, query);
    }

    createCurrency(request: CreateCurrencyRequest): Observable<CurrencyDto> {
        return this.http.post<CurrencyDto>(CURRENCY_ENDPOINTS.create, request);
    }

    updateCurrency(id: string, request: UpdateCurrencyRequest): Observable<CurrencyDto> {
        return this.http.put<CurrencyDto>(CURRENCY_ENDPOINTS.update(id), request);
    }

    getCurrencyById(id: string): Observable<CurrencyDto> {
        return this.http.get<CurrencyDto>(CURRENCY_ENDPOINTS.getById(id));
    }

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

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

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