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

import { LANGUAGE_ENDPOINTS } from './language.endpoints';
import {
  CreateLanguageRequest,
  LanguageDto,
  LanguageLookupDto,
  UpdateLanguageRequest
} from '../models/language.model';
import {
  DataTableQuery,
  DataTableResult
} from '../../../../shared/components/data-table/data-table.types';

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

  getDataTable(query: DataTableQuery): Observable<DataTableResult<LanguageDto>> {
    return this.http.post<DataTableResult<LanguageDto>>(LANGUAGE_ENDPOINTS.dataTable, query);
  }

  getById(id: string): Observable<LanguageDto> {
    return this.http.get<LanguageDto>(LANGUAGE_ENDPOINTS.getById(id));
  }

  create(request: CreateLanguageRequest): Observable<LanguageDto> {
    return this.http.post<LanguageDto>(LANGUAGE_ENDPOINTS.create, request);
  }

  update(id: string, request: UpdateLanguageRequest): Observable<LanguageDto> {
    return this.http.put<LanguageDto>(LANGUAGE_ENDPOINTS.update(id), request);
  }

  autocomplete(
    term: string | null,
    limit = 10
  ): Observable<readonly LanguageLookupDto[]> {
    let params = new HttpParams().set('limit', limit);
    if (term !== null) {
      params = params.set('term', term);
    }

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