import type { H3Event } from 'h3'
import { v4 as uuidv4 } from 'uuid'

/**
 * Get or create a session ID for guest cart management
 *
 * This session ID is stored in a secure HTTP-only cookie and used to
 * identify guest carts. When a user logs in, their guest cart can be
 * merged with their user cart (future enhancement).
 *
 * @param event - H3 event object
 * @returns Session ID (UUID)
 */
export function getOrCreateSessionId(event: H3Event): string {
  const config = useRuntimeConfig()
  const cookieName = config.cart.sessionCookieName

  // Try to get existing session ID from cookie
  const existingSessionId = getCookie(event, cookieName)

  if (existingSessionId) {
    return existingSessionId
  }

  // Generate new session ID
  const newSessionId = uuidv4()

  // Calculate expiry date based on config
  const expiryDays = config.cart.expiryDays
  const maxAge = expiryDays * 24 * 60 * 60 // Convert days to seconds

  // Set session cookie
  setCookie(event, cookieName, newSessionId, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    maxAge,
    path: '/',
  })

  return newSessionId
}

/**
 * Get the current session ID without creating a new one
 *
 * @param event - H3 event object
 * @returns Session ID or null if not found
 */
export function getSessionId(event: H3Event): string | null {
  const config = useRuntimeConfig()
  const cookieName = config.cart.sessionCookieName
  return getCookie(event, cookieName) || null
}

/**
 * Clear the session ID cookie
 *
 * @param event - H3 event object
 */
export function clearSessionId(event: H3Event): void {
  const config = useRuntimeConfig()
  const cookieName = config.cart.sessionCookieName
  deleteCookie(event, cookieName)
}
