import { parseSetCookieHeader } from 'better-auth/cookies'

type HttpContext = {
  request?: {
    headers(): Record<string, string>
  }
  response?: {
    cookie: (name: string, value: string | null, options: Record<string, unknown>) => void
  }
}

const isLocalDomain = (domain: string) => {
  return !domain || domain.includes('localhost') || domain.includes('127.0.0.1')
}

/**
 * Build a `Headers` carrying the caller's credentials to forward into the Better
 * Auth server API (`auth.api.*`). Mirrors Fabric's forwardedAuthHeaders helper.
 */
export const forwardedAuthHeaders = (http?: HttpContext): Headers => {
  const src = http?.request?.headers() ?? {}
  const headers = new Headers()
  if (src.cookie) headers.set('cookie', src.cookie)
  if (src.authorization) headers.set('authorization', src.authorization)
  return headers
}

/**
 * Propagate Better Auth's `Set-Cookie` (e.g. a freshly created session) from a
 * server-API `asResponse` result onto the pikku HTTP response.
 */
export const copyBetterAuthCookies = (response: Response, http?: HttpContext) => {
  if (!http?.response) {
    return
  }

  const rawSetCookie = response.headers.get('set-cookie')
  if (!rawSetCookie) {
    return
  }

  const parsed = parseSetCookieHeader(rawSetCookie)
  for (const [name, cookie] of parsed.entries()) {
    http.response.cookie(name, cookie.value, {
      domain: cookie.domain,
      expires: cookie.expires ? new Date(cookie.expires) : undefined,
      httpOnly: cookie.httpOnly,
      maxAge: cookie.maxAge,
      path: cookie.path || '/',
      sameSite: cookie.sameSite || 'lax',
      secure: cookie.secure,
    })
  }
}

export const getWebsiteOrigin = (domain: string) => {
  if (isLocalDomain(domain)) {
    return 'http://localhost:3001'
  }

  return `https://${domain}`
}
