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

import { TENANT_ENDPOINTS } from './tenant.endpoints';
import { DataTableQuery, DataTableResult } from '../../../shared/components/data-table/data-table.types';
import {
  CreateTenantRequest,
  TenantDto,
  TenantLookupDto,
  UpdateTenantRequest
} from '../models/tenant.model';

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

    getTenantDataTable(query: DataTableQuery): Observable<DataTableResult<TenantDto>> {
        return this.http.post<DataTableResult<TenantDto>>(TENANT_ENDPOINTS.dataTable, query);
    }

    createTenant(request: CreateTenantRequest): Observable<TenantDto> {
        return this.http.post<TenantDto>(TENANT_ENDPOINTS.create, request);
    }

    updateTenant(id: string, request: UpdateTenantRequest): Observable<TenantDto> {
        return this.http.put<TenantDto>(TENANT_ENDPOINTS.update(id), request);
    }

    getTenantById(id: string): Observable<TenantDto> {
        return this.http.get<TenantDto>(TENANT_ENDPOINTS.getById(id));
    }

    autocomplete(term?: string, limit = 10): Observable<readonly TenantLookupDto[]> {
        let params = new HttpParams().set('limit', limit);
        const normalizedTerm = term?.trim();

        if (normalizedTerm) {
            params = params.set('term', normalizedTerm);
        }

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