import { Observable } from 'rxjs';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { createRequestOption } from 'app/core/util/request-util';
import { ApplicationConfigService } from 'app/core/config/application-config.service';
import { inject } from '@angular/core';
import {IEntityServiceModel} from "./entity-config.model";
import {NglFilterField} from "ngl-filter-field";

export abstract class EntityBaseService<ENTITY> implements IEntityServiceModel<ENTITY>{
        protected readonly _http = inject(HttpClient);
        readonly resourceUrl: string;

        protected constructor(
            private readonly api: string,
            private readonly microservice?: string,
        ) {
        this.resourceUrl = inject(ApplicationConfigService).getEndpointFor(api, microservice);
        }

        create(entity: ENTITY): Observable<HttpResponse<ENTITY>> {
            return this._http.post<ENTITY>(this.resourceUrl, entity, { observe: 'response' });
        }

        update(entity: ENTITY): Observable<HttpResponse<ENTITY>> {
            return this._http.put<ENTITY>(`${this.resourceUrl}/${this.getIdentity(entity)}`, entity, { observe: 'response' });
        }

        find(id: number): Observable<ENTITY> {
            return this._http.get<ENTITY>(`${this.resourceUrl}/${id}`, { observe: 'body' });
        }

        query(req?: any): Observable<HttpResponse<ENTITY[]>> {
            const options = createRequestOption(req);
            return this._http.get<ENTITY[]>(this.resourceUrl, { params: options, observe: 'response' });
        }

        delete(id: number | string): Observable<HttpResponse<{}>> {
            return this._http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' });
        }

        getFilterFields(): NglFilterField[] {
            return [];
        }

        abstract getIdentity(model: ENTITY): string | number;
}
