import { HttpClient, HttpParams } from "@angular/common/http";
import { Injectable, inject } from "@angular/core";
import { STATE_ENDPOINTS } from "./state.endpoints"
import { Observable } from "rxjs";
import { DataTableQuery, DataTableResult } from "../../../../shared/components/data-table/data-table.types";
import {
  CreateStateRequest,
  StateDto,
  StateLookupDto,
  UpdateStateRequest
} from "../models/state.model";

@Injectable({
  providedIn: 'root'
})
export class StateService {

    private readonly http = inject(HttpClient);

    getStateDataTable(query: DataTableQuery, countryId: string | null = null): Observable<DataTableResult<StateDto>> {
        const params = countryId ? new HttpParams().set('countryId', countryId) : undefined;
        return this.http.post<DataTableResult<StateDto>>(`${STATE_ENDPOINTS.dataTable}`, query, { params });
    }

    createState(request: CreateStateRequest): Observable<StateDto> {
        return this.http.post<StateDto>(STATE_ENDPOINTS.create, request);
    }

    updateState(id: string, request: UpdateStateRequest): Observable<StateDto> {
        return this.http.put<StateDto>(STATE_ENDPOINTS.update(id), request);
    }

    getStateById(id: string): Observable<StateDto> {
        return this.http.get<StateDto>(STATE_ENDPOINTS.getById(id));
    }

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