import { cookies } from 'next/headers';

const API_BASE_URL = process.env.API_BASE_URL;

export interface ApiResponse<T = any> {
  success: boolean;
  message?: string;
  data?: T;
  errors?: Record<string, string[]>;
}

export interface ServerApiOptions extends RequestInit {
  cache?: RequestCache;
  revalidate?: number | false;
  query?: Record<string, any>;
}

/**
 * Server-side API client - Never exposes tokens to client
 * This should ONLY be used in Server Components, Server Actions, and API Routes
 * @param endpoint - API endpoint (without base URL)
 * @param options - Request options with optional cache, revalidate, and query parameters
 */
export async function serverApiClient<T = any>(
  endpoint: string,
  options: ServerApiOptions = {}
): Promise<ApiResponse<T>> {
  const cookieStore = await cookies();
  const token = cookieStore.get('token')?.value;

  const { cache, revalidate, query, ...fetchOptions } = options;

  // Build query string if query parameters are provided
  let url = `${API_BASE_URL}/${endpoint}`;

  if (query && Object.keys(query).length > 0) {
    const queryParams = new URLSearchParams();
    Object.entries(query).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        queryParams.append(key, String(value));
      }
    });
    const queryString = queryParams.toString();
    if (queryString) {
      url += `?${queryString}`;
    }
  }

  try {
    const headers = {
      'Content-Type': 'application/json',
      ...(token && { Authorization: `Bearer ${token}` }),
      ...fetchOptions.headers,
    };

    const fetchConfig: any = {
      ...fetchOptions,
      headers,
    };

    if (revalidate !== undefined) {
      fetchConfig.next = { revalidate };
    } else {
      fetchConfig.cache = cache || 'no-store';
    }

    if (cache && revalidate === undefined) {
      fetchConfig.cache = cache;
    }

    const response = await fetch(url, fetchConfig);

    // Check if response is JSON
    const contentType = response.headers.get('content-type');
    if (!contentType || !contentType.includes('application/json')) {
      console.error(`[ServerApiClient] API Error [${endpoint}]: Expected JSON but received ${contentType}`);
      return {
        success: false,
        message: `API returned non-JSON response (${response.status})`,
      };
    }

    const data = await response.json();

    if (!response.ok) {
      return {
        success: false,
        message: data.message || `API Error: ${response.status}`,
        errors: data.errors,
      };
    }

    return {
      success: true,
      data: data.data || data,
      message: data.message,
    };
  } catch (error: any) {
    console.error(
      error instanceof Error ? error.message : 'Server API request failed'
    );
    return {
      success: false,
      message: error.message || 'Network error occurred',
    };
  }
}

/**
 * Server-side POST with FormData
 * This should ONLY be used in Server Components, Server Actions, and API Routes
 */
export async function serverPostFormData<T = any>(
  endpoint: string,
  formData: FormData
): Promise<ApiResponse<T>> {
  const cookieStore = await cookies();
  const token = cookieStore.get('token')?.value;

  try {
    const url = `${API_BASE_URL}/${endpoint}`;
    
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        ...(token && { Authorization: `Bearer ${token}` }),
      },
      body: formData,
      cache: 'no-store',
    });

    // Check if response is JSON
    const contentType = response.headers.get('content-type');
    if (!contentType || !contentType.includes('application/json')) {
      console.error(`API Error [${endpoint}]: Expected JSON but received ${contentType}`);
      return {
        success: false,
        message: `API returned non-JSON response (${response.status})`,
      };
    }

    const data = await response.json();

    if (!response.ok) {
      return {
        success: false,
        message: data.message || `API Error: ${response.status}`,
        errors: data.errors,
      };
    }

    return {
      success: true,
      data: data.data || data,
      message: data.message,
    };
  } catch (error: any) {
    console.error(
      error instanceof Error ? error.message : 'Form upload request failed'
    );
    return {
      success: false,
      message: error.message || 'Network error occurred',
    };
  }
}

/**
 * Get auth token (server-side only)
 */
export async function getServerAuthToken(): Promise<string | undefined> {
  const cookieStore = await cookies();
  return cookieStore.get('token')?.value;
}

/**
 * Get user data (server-side only)
 */
export async function getServerUser() {
  const cookieStore = await cookies();
  const userCookie = cookieStore.get('getUser')?.value;
  
  if (!userCookie) return null;
  
  try {
    return JSON.parse(userCookie);
  } catch {
    return null;
  }
}

/**
 * Check if user is authenticated (server-side only)
 */
export async function isAuthenticated(): Promise<boolean> {
  const token = await getServerAuthToken();
  return !!token;
}
