import { cookies } from 'next/headers'
import { NextRequest } from 'next/server'
import {
  verifyH5Cookie,
  getH5CookieSecret,
  h5CookieName,
  type H5CookiePayload,
} from './cookie'
import { h5PageRepo } from '@/lib/database/repositories/h5-page.repo'
import type { H5PageContext } from './router'

/**
 * H5 API 路由鉴权辅助（§6.1）。
 *
 * 从请求 cookie 解出 (pageId, appId, externalUserId)，
 * 反查 h5_pages 确认页面仍存在且启用，组装 H5PageContext。
 *
 * 失败时返回 null（调用方返回 401，前端渲染「会话已过期」整页态）。
 */

export interface H5AuthResult {
  payload: H5CookiePayload
  page: H5PageContext
  /** h5_pages 完整行（含 appSecrets 等，少数场景用） */
  pageRow: NonNullable<ReturnType<typeof h5PageRepo.findById>>
}

/**
 * 从 Next.js headers 解出 cookie。
 * 适用于 API route handler（接收 NextRequest）。
 */
export async function authenticateH5Request(): Promise<H5AuthResult | null> {
  const cookieStore = await cookies()
  const cookieValue = cookieStore.get(h5CookieName())?.value

  const payload = verifyH5Cookie(cookieValue, getH5CookieSecret())
  if (!payload) return null

  const pageRow = h5PageRepo.findById(payload.pageId)
  if (!pageRow || !pageRow.enabled) return null

  const page: H5PageContext = {
    id: pageRow.id,
    workspaceId: pageRow.workspaceId,
    defaultModel: pageRow.defaultModel,
    permissionMode: pageRow.permissionMode,
  }

  return { payload, page, pageRow }
}

/**
 * 从原始 Cookie header 字符串解出（用于 route.ts 里无法用 cookies() 的场景）。
 */
export function authenticateH5FromCookieHeader(
  cookieHeader: string | null,
): H5AuthResult | null {
  if (!cookieHeader) return null

  const value = parseCookieValue(cookieHeader, h5CookieName())
  const payload = verifyH5Cookie(value, getH5CookieSecret())
  if (!payload) return null

  const pageRow = h5PageRepo.findById(payload.pageId)
  if (!pageRow || !pageRow.enabled) return null

  const page: H5PageContext = {
    id: pageRow.id,
    workspaceId: pageRow.workspaceId,
    defaultModel: pageRow.defaultModel,
    permissionMode: pageRow.permissionMode,
  }

  return { payload, page, pageRow }
}

/** 从 Cookie header 字符串取指定 key 的值 */
function parseCookieValue(cookieHeader: string, key: string): string | undefined {
  const prefix = `${key}=`
  for (const part of cookieHeader.split(';')) {
    const trimmed = part.trim()
    if (trimmed.startsWith(prefix)) {
      return trimmed.slice(prefix.length)
    }
  }
  return undefined
}

/** 用于 route.ts 取 cookie header（NextRequest.headers）的便捷封装 */
export function getCookieHeaderFromRequest(req: NextRequest): string | null {
  return req.headers.get('cookie')
}
