/* eslint-disable @typescript-eslint/no-explicit-any */
import { getCurrentLocale } from '@/utils/locale';

const API = process.env.NEXT_PUBLIC_API_URL;

if (!API) throw new Error('API_URL is not defined');

function createApiError(endpoint: string, status: number | string, responseText: string) {
  const error = new Error(`API error: ${endpoint} (${status})`);
  (error as any).status = status;
  (error as any).response = responseText;
  return error;
}

export async function javaPost(
  endpoint: string,
  body: any,
  options: { headers?: Record<string, string>; [key: string]: any } = {}
) {
  const locale = await getCurrentLocale();

  const fetchOptions = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Language': locale,
      ...(options.headers || {}),
    },
    body: JSON.stringify(body),
    next: { revalidate: 60 },
    ...options,
  };

  const requestUrl = `${API?.replace(/\/$/, '')}/${endpoint.replace(/^\//, '')}`;

  let res;

  try {
    res = await fetch(requestUrl, fetchOptions);
  } catch (err) {
    if (!(err instanceof DOMException && err.name === 'AbortError')) {
      console.error('Network or fetch error:', err);
      const message =
        typeof err === 'object' && err !== null && 'message' in err
          ? (err as { message: string }).message
          : String(err);
      throw new Error(`Network error: ${message}`);
    }
    // AbortError: fetch was aborted, do not log
    throw err;
  }

  const responseText = await res.text();

  if (!res.ok) {
    console.error('API error:', endpoint, res.status, responseText);
    throw createApiError(endpoint, res.status, responseText);
  }

  try {
    return JSON.parse(responseText);
  } catch {
    return responseText;
  }
}
