'use server';

import { ClientOnline } from "@/types/mutual/context/validations";
import { API_BASE_URL } from "@/config/config";

// Default online state to use when API calls fail
const DEFAULT_ONLINE_STATE: ClientOnline = {
  lastLogin: new Date(),
  lastLogout: new Date(),
  lastAction: new Date(),
  lastPage: "/",
  userType: "guest",
  lang: "en",
  timezone: "UTC"
};

/**
 * Server-side function to fetch online state
 * This can be safely called from server components
 */
export async function getOnlineFromServer(): Promise<ClientOnline> {
  try {
    console.log(`[Server] Fetching online state from ${API_BASE_URL}/context/page/online`);
    
    // Create an AbortController with a timeout
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 second timeout
    
    try {
      const result = await fetch(`${API_BASE_URL}/context/page/online`, {
        method: "GET",
        headers: { 
          "Content-Type": "application/json",
          "Cache-Control": "no-cache"
        },
        signal: controller.signal,
        // Add next.js cache options
        next: {
          revalidate: 60 // Revalidate every 60 seconds
        }
      });
      
      // Clear the timeout
      clearTimeout(timeoutId);
      
      if (!result.ok) {
        throw new Error(`HTTP error! Status: ${result.status}`);
      }
      
      const data = await result.json();
      console.log('[Server] Online state API response:', data);
      
      if (data.status === 200 && data.data) {
        return data.data;
      } else {
        console.warn('[Server] Invalid response format from online state API');
        return DEFAULT_ONLINE_STATE;
      }
    } catch (fetchError) {
      // Clear the timeout if it hasn't fired yet
      clearTimeout(timeoutId);
      
      // Check if this is an abort error (timeout)
      if (fetchError instanceof DOMException && fetchError.name === 'AbortError') {
        console.warn('[Server] Request timed out or was aborted');
        return DEFAULT_ONLINE_STATE;
      }
      
      // Re-throw other errors to be caught by the outer catch
      throw fetchError;
    }
  } catch (error) {
    // Handle all other errors
    if (error instanceof DOMException && error.name === 'AbortError') {
      console.warn('[Server] Request for online state was aborted');
      return DEFAULT_ONLINE_STATE;
    } else {
      console.error('[Server] Error fetching online state:', error instanceof Error ? error.message : 'Unknown error');
      return DEFAULT_ONLINE_STATE;
    }
  }
}

/**
 * Server-side function to update online state
 * This can be safely called from server components
 */
export async function setOnlineFromServer(newOnline: ClientOnline): Promise<boolean> {
  try {
    console.log(`[Server] Updating online state at ${API_BASE_URL}/context/page/online`);
    
    const result = await fetch(`${API_BASE_URL}/context/page/online`, {
      method: "POST",
      headers: { 
        "Content-Type": "application/json",
        "Cache-Control": "no-cache"
      },
      body: JSON.stringify(newOnline)
    });
    
    if (!result.ok) {
      throw new Error(`HTTP error! Status: ${result.status}`);
    }
    
    const data = await result.json();
    console.log('[Server] Update online state API response:', data);
    
    return data.status === 200;
  } catch (error) {
    console.error('[Server] Error updating online state:', error instanceof Error ? error.message : 'Unknown error');
    return false;
  }
}
