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 {
  CountryDto,
  CountryLookupDto,
  CreateCountryRequest,
  UpdateCountryRequest,
} from '../models/country.model';
import { COUNTRY_ENDPOINTS } from './country.endpoints';

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

  getCountryDataTable(query: DataTableQuery): Observable<DataTableResult<CountryDto>> {
    return this.http.post<DataTableResult<CountryDto>>(COUNTRY_ENDPOINTS.dataTable, query);
  }

  createCountry(request: CreateCountryRequest): Observable<CountryDto> {
    return this.http.post<CountryDto>(COUNTRY_ENDPOINTS.create, request);
  }

  updateCountry(id: string, request: UpdateCountryRequest): Observable<CountryDto> {
    return this.http.put<CountryDto>(COUNTRY_ENDPOINTS.update(id), request);
  }

  getCountryById(id: string): Observable<CountryDto> {
    return this.http.get<CountryDto>(COUNTRY_ENDPOINTS.getById(id));
  }

  autocomplete(term = '', limit = 50): Observable<CountryLookupDto[]> {
    return this.http.get<CountryLookupDto[]>(COUNTRY_ENDPOINTS.autocomplete, {
      params: new HttpParams().set('term', term).set('limit', limit),
    });
  }
}
