import type { DjangoHTTPClient } from 'mizan/client'
import { createAPI } from './api'
import type { AllauthResponse } from './types'

export interface InitialAuth {
    config: AllauthResponse
    auth: AllauthResponse
}

/**
 * Fetch initial allauth state using an SSR client.
 * Call this in a server component and pass the result to AllauthContext.
 *
 * Note: User data comes from DjangoContext (which should wrap AllauthContext).
 * Use getDjangoHydration() from generated.contexts for that.
 *
 * @param ssrClient - A server-side Django HTTP client (e.g., createDjangoSSRClient)
 */
export async function getInitialAuth(
    ssrClient: DjangoHTTPClient,
): Promise<InitialAuth> {
    const authRequest = async (method: string, path: string, data?: any, headers?: Record<string, string>) => {
        const resp = await ssrClient.request(method, `/_allauth/browser/v1${path}`, data, headers)
        if (resp.status >= 500) {
            throw new Error(`Allauth request failed: ${resp.status} ${resp.statusText}`)
        }
        return resp.json()
    }

    const api = createAPI((method, path, data?, headers?) =>
        authRequest(method, path, { ...(data as object), client: 'browser' }, headers)
    )

    try {
        const [config, auth] = await Promise.all([
            api.getConfig(),
            api.session.getStatus(),
        ])

        return { config, auth }
    } catch (e) {
        console.error('[getInitialAuth] Failed to fetch initial auth:', e)
        return {
            config: { status: 200, data: {} },
            auth: { status: 401, data: {} },
        }
    }
}
