'use server';

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

// Default user state to use when API calls fail
const DEFAULT_USER_STATE: ClientUser = {
  uuid: 'default-user-id',
  avatar: '',
  email: '',
  phone_number: '',
  user_tag: 'guest',
  password_expiry_begins: new Date().toISOString(),
  person: {
    uuid: 'default-person-id',
    firstname: 'Guest',
    surname: 'User',
    middle_name: '',
    sex_code: '',
    person_tag: 'guest',
    country_code: '',
    birth_date: ''
  }
};

/**
 * Server-side function to fetch user data
 * This can be safely called from server components
 */
export async function getUserFromServer(): Promise<ClientUser> {
  try {
    console.log(`[Server] Fetching user data from ${API_BASE_URL}/context/dash/user`);
    
    // 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/dash/user`, {
        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] User data API response:', JSON.stringify(data, null, 2));
      
      // Handle different response formats
      if (data.status === 200 && data.data) {
        // Standard API response format
        console.log('[Server] Found standard API response format with data');
        return data.data;
      } else if (data.user) {
        // Direct Redis object format
        console.log('[Server] Found user data in Redis format:', JSON.stringify(data.user, null, 2));
        return data.user;
      } else if (data.uuid) {
        // Direct user object format
        console.log('[Server] Found direct user data format');
        return data;
      } else if (data.email || (data.person && data.person.firstname)) {
        // Partial user object format
        console.log('[Server] Found partial user data format');
        return {
          ...DEFAULT_USER_STATE,
          ...data,
          uuid: data.uuid || DEFAULT_USER_STATE.uuid
        };
      } else {
        console.warn('[Server] Invalid response format from user API');
        return DEFAULT_USER_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_USER_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 user data was aborted');
      return DEFAULT_USER_STATE;
    } else {
      console.error('[Server] Error fetching user data:', error instanceof Error ? error.message : 'Unknown error');
      return DEFAULT_USER_STATE;
    }
  }
}

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