"use server";

/**
 * NOTE: This file contains workarounds for missing backend endpoints.
 * In the future, consider implementing proper API endpoints for these functions:
 * - GET /chats/:chatId/members - To get chat members
 * - GET /users/:userId - To get user information
 */

/**
 * Helper function to make a server-side fetch with proper error handling
 */
async function safeFetch(path: string) {
  try {
    // Use absolute URL with the API_URL from environment variable or default to local
    const baseUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
    
    // Remove any leading /api/ or api/ to prevent double prefixing
    let cleanPath = path.replace(/^\/?(api\/)+/, '');
    
    // Ensure path starts with a / for consistent joining
    if (!cleanPath.startsWith('/')) {
      cleanPath = '/' + cleanPath;
    }
    
    // Construct the URL with a single /api prefix
    const url = `${baseUrl}/api${cleanPath}`;
    
    console.log(`Server action fetching URL: ${url}`);
    
    // For server components, use the fetch API directly
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error(`API error: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error(`Error fetching ${path}:`, error);
    return null;
  }
}

/**
 * Get chat details and extract members information
 */
export async function getChatMembers(chatId: string) {
  try {
    // Use the safeFetch helper with the correct path - avoid any api prefix
    const response = await safeFetch(`chats/${chatId}`);
    
    if (response) {
      // Create member objects for buyer and vendor
      const members = [
        {
          _id: response.buyerId,
          isVendor: false,
          telegramUsername: response.telegramUsername || null
        },
        {
          _id: response.vendorId,
          isVendor: true
        }
      ];
      
      return { members };
    }
    
    return { members: [] };
  } catch (error) {
    console.error("Error in getChatMembers:", error);
    return { members: [] };
  }
}

/**
 * Get user information by ID
 * This function is imported but doesn't appear to be used in the component.
 * Keeping a placeholder implementation for future use.
 */
export async function getUserInfoById(userId: string) {
  try {
    // This function isn't actually used currently, but we'll keep a
    // placeholder implementation in case it's needed in the future
    return { 
      user: {
        _id: userId,
        name: userId && userId.length > 8 
          ? `Customer ${userId.slice(-4)}`  // For buyers
          : "Vendor",                       // For vendors
        isVendor: userId && userId.length <= 8
      }
    };
  } catch (error) {
    console.error("Error in getUserInfoById:", error);
    return { user: null };
  }
} 