const API_BASE_URL = "http://localhost/backend/api";

const buildQuery = (params = {}) => {
  const query = new URLSearchParams();

  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && value !== "") {
      query.append(key, value);
    }
  });

  return query.toString() ? `?${query.toString()}` : "";
};

export const api = {
  async list(entity) {
    const res = await fetch(`${API_BASE_URL}/${entity}.php`);
    return await res.json();
  },

  async get(entity, id) {
    const res = await fetch(`${API_BASE_URL}/${entity}.php?id=${id}`);
    return await res.json();
  },

  async filter(entity, params = {}) {
    const res = await fetch(
      `${API_BASE_URL}/${entity}.php${buildQuery(params)}`
    );

    return await res.json();
  },

  async create(entity, payload) {
    const res = await fetch(`${API_BASE_URL}/${entity}.php`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(payload)
    });

    return await res.json();
  },

  async update(entity, id, payload) {
    const res = await fetch(
      `${API_BASE_URL}/${entity}.php?id=${id}`,
      {
        method: "PUT",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(payload)
      }
    );

    return await res.json();
  },

  async remove(entity, id) {
    const res = await fetch(
      `${API_BASE_URL}/${entity}.php?id=${id}`,
      {
        method: "DELETE"
      }
    );

    return await res.json();
  }
};