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

import { TIMEZONE_ENDPOINTS } from './timezone.endpoints';
import {
  CreateTimezoneRequest,
  TimezoneDto,
  TimezoneLookupDto,
  UpdateTimezoneRequest
} from '../models/timezone.model';
import {
  DataTableQuery,
  DataTableResult
} from '../../../../shared/components/data-table/data-table.types';

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

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

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

  create(request: CreateTimezoneRequest): Observable<TimezoneDto> {
    return this.http.post<TimezoneDto>(TIMEZONE_ENDPOINTS.create, request);
  }

  update(id: string, request: UpdateTimezoneRequest): Observable<TimezoneDto> {
    return this.http.put<TimezoneDto>(TIMEZONE_ENDPOINTS.update(id), request);
  }

  autocomplete(term: string | null, limit = 10): Observable<readonly TimezoneLookupDto[]> {
    const normalizedTerm = term?.trim() || null;
    let params = new HttpParams().set('limit', limit);
    if (normalizedTerm !== null) {
      params = params.set('term', normalizedTerm);
    }
    return this.http.get<readonly TimezoneLookupDto[]>(TIMEZONE_ENDPOINTS.autocomplete, { params });
  }
}
