import { redirect } from 'next/navigation'
import { getSession } from '@/lib/auth'
import { isPairedSessionExpired } from '@/lib/auth/pairing'
import { prisma } from '@/lib/prisma'

/**
 * Layout-side auth guard. Returns the session when valid; otherwise redirects
 * to /login (and destroys an expired paired-session first).
 *
 * Used by both `app/(app)/layout.tsx` (desktop) and `app/(mobile)/layout.tsx`.
 */
export async function requireSession() {
  const session = await getSession()

  if (!session.userId) {
    redirect('/login')
  }

  if (isPairedSessionExpired(session)) {
    await session.destroy()
    redirect('/login')
  }

  return session
}

export async function requireAdmin() {
  const session = await getSession()
  if (!session.userId) {
    redirect('/dashboard')
  }
  const adminRole = await prisma.userRole.findFirst({
    where: { user_id: session.userId, role: 'ADMIN' },
  })
  if (!adminRole) {
    redirect('/dashboard')
  }
  return session
}
