import { createSignal } from "solid-js"

// Storage key for active user
const ACTIVE_USER_KEY = "codenomad_active_user_id"

const [isLoggedIn, setLoggedIn] = createSignal(false)

export { isLoggedIn, setLoggedIn }

/**
 * Set the active user ID
 */
export function setActiveUserId(userId: string | null): void {
    if (userId) {
        localStorage.setItem(ACTIVE_USER_KEY, userId)
        setLoggedIn(true)
        console.log(`[UserContext] Active user set to: ${userId}`)
    } else {
        localStorage.removeItem(ACTIVE_USER_KEY)
        setLoggedIn(false)
        console.log(`[UserContext] Active user cleared`)
    }
}

/**
 * Get the active user ID
 */
export function getActiveUserId(): string | null {
    return localStorage.getItem(ACTIVE_USER_KEY)
}

/**
 * Get headers with user ID for API requests
 */
export function getUserHeaders(): Record<string, string> {
    const userId = getActiveUserId()
    if (userId) {
        return { "X-User-Id": userId }
    }
    return {}
}

/**
 * Create fetch options with user headers
 */
export function withUserHeaders(options: RequestInit = {}): RequestInit {
    const userHeaders = getUserHeaders()
    return {
        ...options,
        headers: {
            ...options.headers,
            ...userHeaders,
        },
    }
}

/**
 * Fetch wrapper that automatically includes user headers
 */
export async function userFetch(url: string, options: RequestInit = {}): Promise<Response> {
    return fetch(url, withUserHeaders(options))
}

/**
 * Initialize user context from Electron IPC
 * Call this on app startup
 */
export async function initializeUserContext(): Promise<void> {
    try {
        // Check if we're in Electron environment
        const ipcRenderer = (window as any).electron?.ipcRenderer
        if (ipcRenderer) {
            const activeUser = await ipcRenderer.invoke("users:active")
            if (activeUser?.id) {
                setActiveUserId(activeUser.id)
                console.log(`[UserContext] Initialized with user: ${activeUser.id} (${activeUser.name})`)
            } else {
                setLoggedIn(false)
                console.log(`[UserContext] No active user from IPC`)
            }
        } else {
            // Web mode - try to get from localStorage or use default
            const existingId = getActiveUserId()
            if (existingId) {
                setLoggedIn(true)
                console.log(`[UserContext] Using cached user ID: ${existingId}`)
            } else {
                setLoggedIn(false)
                console.log(`[UserContext] Web mode - no active user`)
            }
        }
    } catch (error) {
        console.error(`[UserContext] Failed to initialize:`, error)
        setLoggedIn(false)
    }
}
