"use client";

import { useMemo } from "react";

// API routes now handled by Next.js /api routes (server-side)
// Authentication happens via HTTP-only cookies automatically

type JsonValue = any;

export function useApi() {
  return useMemo(() => {
    async function get(path: string, init?: RequestInit) {
      // Path should now point to Next.js API routes (e.g., /api/builds)
      return fetch(path, {
        ...init,
        credentials: 'include', // Include cookies in requests
      });
    }

    async function post(path: string, body: JsonValue, init?: RequestInit) {
      return fetch(path, {
        method: "POST",
        ...init,
        credentials: 'include',
        headers: {
          "Content-Type": "application/json",
          ...(init?.headers as any),
        },
        body: JSON.stringify(body),
      });
    }

    async function put(path: string, body: JsonValue, init?: RequestInit) {
      return fetch(path, {
        method: "PUT",
        ...init,
        credentials: 'include',
        headers: {
          "Content-Type": "application/json",
          ...(init?.headers as any),
        },
        body: JSON.stringify(body),
      });
    }

    async function del(path: string, init?: RequestInit) {
      return fetch(path, {
        method: "DELETE",
        ...init,
        credentials: 'include',
        headers: init?.headers,
      });
    }

    return { get, post, put, del };
  }, []);
}