import { api } from "../http/instances";
import * as T from "./dtos";

const MAX_PAGES = 1000;

export const CrudService = {
  async retrieve<TResponse>(entity: string, idValue: string): Promise<TResponse> {
    const response = await api.post<TResponse>("/retrieve", {
      entity,
      idValue,
    } satisfies T.RetrieveRequest);
    return response.data;
  },

  async retrievePage<TResponse>(
    entity: string,
    page: number,
  ): Promise<T.RetrievePageResponse<TResponse>> {
    const response = await api.post<T.RetrievePageResponse<TResponse>>("/retrievePage", {
      entity,
      page: String(page),
    } satisfies T.RetrievePageRequest);
    return response.data;
  },

  async retrieveAllPages<TResponse>(entity: string): Promise<TResponse[]> {
    const all: TResponse[] = [];

    for (let page = 1; page <= MAX_PAGES; page++) {
      const { data } = await this.retrievePage<TResponse>(entity, page);
      if (!data || data.length === 0) break;
      all.push(...data);
    }

    return all;
  },

  async update<TPayload, TResponse = TPayload>(
    entity: string,
    idValue: string,
    data: Partial<TPayload>,
  ): Promise<TResponse> {
    const response = await api.post<TResponse>("/update", {
      entity,
      idValue,
      data,
    } satisfies T.UpdateRequest<TPayload>);
    return response.data;
  },

  async remove(entity: string, idValue: string): Promise<T.DeleteResponse> {
    const response = await api.post<T.DeleteResponse>("/delete", {
      entity,
      idValue,
    } satisfies T.DeleteRequest);
    return response.data;
  },
};
