import "server-only"
import { cookies } from "next/headers"
import { createApi } from "./api"
import type { AuthUser } from "./infra/token"

export async function getServerApi() {
    const cookieStore = await cookies()
    const token = cookieStore.get("auth_token")?.value
    // Multi-tenant: the workspace's backend URL and id live in httpOnly cookies
    // set by middleware. Client requests reach the right tenant via the
    // /api/proxy route; SSR must replicate that — point at the tenant's
    // api_base_url and send X-Workspace-UUID, or the request hits the wrong
    // (default) backend and resources come back "not found".
    const apiBaseUrl = cookieStore.get("api_base_url")?.value
    const workspaceUuid = cookieStore.get("workspace_uuid")?.value

    const headers: Record<string, string> = {}
    if (token) headers.Authorization = `Bearer ${token}`
    if (workspaceUuid) headers["X-Workspace-UUID"] = workspaceUuid

    return createApi({
        ...(apiBaseUrl ? { baseUrl: apiBaseUrl } : {}),
        ...(Object.keys(headers).length ? { headers } : {}),
    })
}

export async function getServerUser(): Promise<AuthUser | null> {
    const cookieStore = await cookies()
    const raw = cookieStore.get("auth_user")?.value
    if (!raw) return null
    try {
        return JSON.parse(decodeURIComponent(raw)) as AuthUser
    } catch {
        return null
    }
}
