'use server';

import { cookies } from 'next/headers';
import { serverApiClient } from '@/utils/serverApiClient';


export async function getCoCreationSession(productId: string) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('token')?.value;

    // Extract userId from the getUser cookie
    const userCookie = cookieStore.get('getUser')?.value;
    let userId = null;
    
    if (userCookie) {
      try {
        const userData = JSON.parse(userCookie);
        console.log('userData', userData);
        userId = userData.id;
      } catch (e) {
        console.error('Error parsing user cookie:', e);
      }
    }

    // Always call the backend API first (for both logged-in and guest users)
    const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
    };
    
    // Add token to headers if available
    if (token) {
      headers['Cookie'] = `token=${token}`;
    }

    const response = await fetch(`${baseUrl}/api/products/${productId}/co-creation?user=${userId || ''}`, {
      method: 'GET',
      headers,
      cache: 'no-store',
    });

    if (!response.ok) {
      throw new Error(`Error: ${response.status} - ${response.statusText}`);
    }

    const data = await response.json();

    // Check if backend requires login (for guest users)
    if (!token && data?.url) {
      // Guest user: backend returned URL, but user needs to login first
      return {
        success: false,
        message: 'Please login to customize this product',
        requiresLogin: true,
        url: data.url, // Return the URL so frontend can use it after login
      };
    }

    // Validate response structure for logged-in users
    if (!data?.session_id || !data?.url) {
      console.error('Invalid API response:', data);
      return {
        success: false,
        message: 'Unable to start customization. Please try again.',
      };
    }

    // Logged-in user: return success with session_id and URL
    return {
      success: true,
      session_id: data.session_id,
      url: data.url,
    };
  } catch (error: any) {
    console.error('Error fetching co-creation session:', error);
    return {
      success: false,
      message: 'Failed to start customization. Please try again.',
    };
  }
}
