'use client';

import { apiFetch } from "../../helpers/fetcher";
import { useEffect, useState } from "react";

const BASE_URL = 'admin';

const API_URL = `http://localhost:5000/${BASE_URL}`;

export function useAdminReferentiel(endpoint: string) {
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  async function load() {
    const result = await apiFetch(`${API_URL}${endpoint}`);
    setData(result);
    setLoading(false);
  }

  useEffect(() => {
    load();
  }, [endpoint]);

  async function create(payload: any) {
    await apiFetch(`${API_URL}${endpoint}`,
      {
        method: "POST",
        body: JSON.stringify(payload)
      }
    );
    load();
  }

  async function update(id: number, payload: any) {
    await apiFetch(`${API_URL}${endpoint}/${id}`,
      {
        method: "PUT",
        body: JSON.stringify(payload)
      }
    );
    load();
  }

  async function remove(id: number) {
    await apiFetch(`${API_URL}${endpoint}/${id}`,
      {
        method: "DELETE"
      }
    );
    load();
  }

  return {
    data,
    loading,
    create,
    update,
    remove
  };
}