import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { HelpersService } from "./helpers.service";
import { ObjectResponse } from "../interfaces/api-object-response";
import { ArrayResponse } from "../interfaces/api-array-response";
import { HTTPQuery } from "../interfaces/http-query";

@Injectable({
  providedIn: "root",
})
export class ApiService<T> {
  private baseApiUrl = "/api";
  endpoint = "";
  query: HTTPQuery = {};

  constructor(public http: HttpClient, public helpers: HelpersService) {}

  url(): string {
    return `${this.baseApiUrl}/${this.endpoint}`;
  }

  urlWithId(id: string | number): string {
    return `${this.baseApiUrl}/${this.endpoint}/${id}`;
  }

  urlCustom(c: string): string {
    return `${this.baseApiUrl}/${this.endpoint}/${c}`;
  }

  urlArray(c: string[]): string {
    return `${this.baseApiUrl}/${this.endpoint}/${c.join("/")}`;
  }

  insert(data: any): Observable<ObjectResponse<T>> {
    const url = this.url();
    return this.http.post<ObjectResponse<T>>(url, data);
  }

  getAll(query?: HTTPQuery): Observable<ArrayResponse<T>> {
    const url = this.url();
    const params = query ? this.helpers.generateParams(query) : {};
    return this.http.get<ArrayResponse<T>>(url, { params });
  }

  getById(
    id: string | number,
    query?: HTTPQuery
  ): Observable<ObjectResponse<T>> {
    const url = this.urlWithId(id);
    const params = query ? this.helpers.generateParams(query) : {};
    return this.http.get<ObjectResponse<T>>(url, { params });
  }

  update(id: string | number, data: any): Observable<ObjectResponse<T>> {
    const url = this.urlWithId(id);
    return this.http.put<ObjectResponse<T>>(url, data);
  }

  delete(id: string | number): Observable<ObjectResponse<T>> {
    const url = this.urlWithId(id);
    return this.http.delete<ObjectResponse<T>>(url);
  }
}
