const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000/api';

export interface ApiResponse<T = any> {
  success: boolean;
  message?: string;
  error?: string;
  [key: string]: any;
}

export async function apiRequest<T = any>(
  endpoint: string,
  options: RequestInit = {}
): Promise<ApiResponse<T>> {
  const token = typeof window !== 'undefined' ? localStorage.getItem('ags_token') : null;

  const headers: Record<string, string> = {
    ...(options.headers as Record<string, string> || {}),
  };

  if (!(options.body instanceof FormData) && !headers['Content-Type']) {
    headers['Content-Type'] = 'application/json';
  }

  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  try {
    const res = await fetch(`${API_BASE}${endpoint}`, {
      ...options,
      headers,
    });

    const text = await res.text();
    let data: any = {};
    if (text) {
      try {
        data = JSON.parse(text);
      } catch {
        data = { success: false, error: `Server error (${res.status}): ${res.statusText || 'Invalid response'}` };
      }
    } else {
      data = { success: res.ok, error: res.ok ? undefined : `Server returned empty response (${res.status})` };
    }

    if (!res.ok && !data.error) {
      data.error = `HTTP Error ${res.status}: ${res.statusText}`;
      data.success = false;
    }

    return data;
  } catch (error: any) {
    return {
      success: false,
      error: error.message || 'Unable to connect to server. Please check your backend connection.',
    };
  }
}

export async function uploadFile(file: File, category: 'video' | 'script' | 'homework' | 'general' = 'general'): Promise<ApiResponse> {
  const token = typeof window !== 'undefined' ? localStorage.getItem('ags_token') : null;

  const formData = new FormData();
  formData.append('file', file);
  formData.append('category', category);

  const headers: Record<string, string> = {};
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  try {
    const res = await fetch(`${API_BASE}/upload`, {
      method: 'POST',
      body: formData,
      headers,
    });

    const text = await res.text();
    let data: any = {};
    if (text) {
      try {
        data = JSON.parse(text);
        if (data && data.success) {
          data.fileUrl = data.url || data.fileUrl || data.relativeUrl;
        }
      } catch {
        data = { success: false, error: `Upload server error (${res.status})` };
      }
    }

    return data;
  } catch (error: any) {
    return {
      success: false,
      error: error.message || 'File upload failed. Please try again.',
    };
  }
}
