import type { ApiResponse } from '../types/api';

const BASE_URL = '/snp-connection/api';

let currentUserId: number = 1;

export const setApiClientUserId = (userId: number) => {
  currentUserId = userId;
};

const request = async <T>(url: string, options: RequestInit = {}): Promise<ApiResponse<T>> => {
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    'X-User-Id': String(currentUserId),
    ...options.headers as Record<string, string>,
  };

  const response = await fetch(`${BASE_URL}${url}`, {
    ...options,
    headers,
  });

  const data = await response.json() as ApiResponse<T>;
  return data;
};

export const get = <T>(url: string): Promise<ApiResponse<T>> => {
  return request<T>(url, { method: 'GET' });
};

export const post = <T>(url: string, body?: unknown): Promise<ApiResponse<T>> => {
  return request<T>(url, {
    method: 'POST',
    body: body ? JSON.stringify(body) : undefined,
  });
};

export const put = <T>(url: string, body?: unknown): Promise<ApiResponse<T>> => {
  return request<T>(url, {
    method: 'PUT',
    body: body ? JSON.stringify(body) : undefined,
  });
};

export const del = <T>(url: string): Promise<ApiResponse<T>> => {
  return request<T>(url, { method: 'DELETE' });
};
