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

export class ApiClient {
    private baseHeaders: HeadersInit = {
        'Content-Type': 'application/json',
    };

    public async get<T>(url: string): Promise<ApiResponse<T>> {
        return this.request<T>(url, { method: 'GET' });
    }

    public async post<T>(url: string, body: unknown): Promise<ApiResponse<T>> {
        return this.request<T>(url, {
            method: 'POST',
            headers: this.baseHeaders,
            body: JSON.stringify(body)
        });
    }

    public async postFormData<T>(url: string, body: FormData): Promise<ApiResponse<T>> {
        // No Content-Type header: the browser sets multipart/form-data with the
        // correct boundary itself - overriding it here would break parsing server-side.
        return this.request<T>(url, { method: 'POST', body });
    }

    public async patch<T>(url: string, body: unknown): Promise<ApiResponse<T>> {
        // OVH shared hosting blocks PATCH/DELETE verbs at the Apache level (403
        // before reaching PHP). Send a real POST and let Symfony's built-in
        // X-HTTP-METHOD-OVERRIDE support route it as PATCH (see Request::getMethod()).
        return this.request<T>(url, {
            method: 'POST',
            headers: { ...this.baseHeaders, 'X-HTTP-METHOD-OVERRIDE': 'PATCH' },
            body: JSON.stringify(body)
        });
    }

    public async delete<T>(url: string): Promise<ApiResponse<T>> {
        return this.request<T>(url, {
            method: 'POST',
            headers: { 'X-HTTP-METHOD-OVERRIDE': 'DELETE' }
        });
    }

    private async request<T>(url: string, options: RequestInit): Promise<ApiResponse<T>> {
        try {
            const response = await fetch(url, options);
            const data: ApiResponse<T> = await response.json();
            return data;
        } catch (error) {
            console.error('[ApiClient] Request failed:', error);
            return {
                success: false,
                error: error instanceof Error ? error.message : 'Unknown error'
            };
        }
    }
}
