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

import { CITY_ENDPOINTS } from './city.endpoints';
import {
  CityDto,
  CreateCityRequest,
  UpdateCityRequest
} from '../models/city.model';
import {
  DataTableQuery,
  DataTableResult
} from '../../../../shared/components/data-table/data-table.types';

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

  getCityDataTable(
    query: DataTableQuery,
    countryId: string | null = null,
    stateId: string | null = null
  ): Observable<DataTableResult<CityDto>> {
    let params = new HttpParams();
    if (countryId) params = params.set('countryId', countryId);
    if (stateId) params = params.set('stateId', stateId);
    return this.http.post<DataTableResult<CityDto>>(
      CITY_ENDPOINTS.dataTable,
      query,
      { params }
    );
  }

  createCity(request: CreateCityRequest): Observable<CityDto> {
    return this.http.post<CityDto>(CITY_ENDPOINTS.create, request);
  }

  updateCity(id: string, request: UpdateCityRequest): Observable<CityDto> {
    return this.http.put<CityDto>(CITY_ENDPOINTS.update(id), request);
  }

  getCityById(id: string): Observable<CityDto> {
    return this.http.get<CityDto>(CITY_ENDPOINTS.getById(id));
  }
}
