export const dynamic = 'force-dynamic'

import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import db from '@/lib/db'
import AppShell from '@/components/layout/AppShell'

export default async function AppLayout({ children }: { children: React.ReactNode }) {
  const cookieStore = await cookies()

  // 从 middleware 设置的 session cookie 获取用户名
  const sessionCookie = cookieStore.get('session')?.value
  let username = ''
  if (sessionCookie) {
    try { username = JSON.parse(sessionCookie).username || '' } catch { }
  }
  if (!username) redirect('/login')

  // 从数据库获取用户完整信息
  const user = db.prepare(
    'SELECT id, username, display_name, role FROM users WHERE username = ? AND is_active = 1'
  ).get(username) as { id: number; username: string; display_name: string; role: string } | undefined

  if (!user) redirect('/login')

  return <AppShell user={{ display_name: user.display_name, role: user.role }}>{children}</AppShell>
}
