import { useAuthStore } from "@/lib/api/auth-store"
import { useSessionGuardStore } from "@/lib/auth/session-guard-store"
import type { PlatformUser } from "@/lib/auth/jwt-claims"

export type SessionPayload = {
  authenticated?: boolean
  accessToken?: string
  refreshToken?: string | null
  expiresAt?: number
  user?: PlatformUser | null
  expired?: boolean
}

export async function fetchSession(): Promise<SessionPayload | null> {
  try {
    const res = await fetch("/api/auth/session", { credentials: "include" })
    if (!res.ok) return null
    return (await res.json()) as SessionPayload
  } catch {
    return null
  }
}

export function applySessionToStore(data: SessionPayload): boolean {
  if (data.authenticated && data.accessToken && data.expiresAt) {
    useAuthStore.getState().login(
      data.accessToken,
      data.refreshToken ?? "",
      data.expiresAt,
      data.user ?? null
    )
    useSessionGuardStore.getState().clear()
    return true
  }
  return false
}

export async function tryRefreshSession(): Promise<boolean> {
  const data = await fetchSession()
  return data !== null && applySessionToStore(data)
}
