/**
 * Base API Client for HTTP operations
 *
 * Provides generic HTTP methods with common request/response handling,
 * error handling, and authentication.
 */

export class BaseApiClient {
  private baseUrl: string;

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }

  protected async request<T>(method: string, path: string, data?: object): Promise<T> {
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
    };

    const config: RequestInit = {
      method,
      headers,
      credentials: 'include', // Include cookies for auth
    };

    if (data) {
      config.body = JSON.stringify(data);
    }

    const response = await fetch(`${this.baseUrl}${path}`, config);

    if (!response.ok) {
      let errorData: { message?: string } = { message: response.statusText };
      try {
        errorData = await response.json();
      } catch {
        // Keep default error message
      }
      throw new Error(errorData.message || `API request failed with status ${response.status}`);
    }

    const text = await response.text();
    if (!text) {
      return null as T;
    }
    return JSON.parse(text) as T;
  }

  protected get<T>(path: string): Promise<T> {
    return this.request<T>('GET', path);
  }

  protected post<T>(path: string, data: object): Promise<T> {
    return this.request<T>('POST', path, data);
  }

  protected put<T>(path: string, data: object): Promise<T> {
    return this.request<T>('PUT', path, data);
  }

  protected delete<T>(path: string): Promise<T> {
    return this.request<T>('DELETE', path);
  }

  protected patch<T>(path: string, data: object): Promise<T> {
    return this.request<T>('PATCH', path, data);
  }
}