import { redirect } from 'next/navigation'
import { getSession } from '@/lib/auth'
import { productAccessFilter } from '@/lib/product-access'
import { prisma } from '@/lib/prisma'
import { ProductPicker } from '@/components/solo/product-picker'

export default async function SoloPage() {
  const session = await getSession()
  if (!session.userId) redirect('/login')

  const user = await prisma.user.findUnique({
    where: { id: session.userId },
    select: { active_product_id: true },
  })

  if (user?.active_product_id) {
    const product = await prisma.product.findFirst({
      where: { id: user.active_product_id, archived: false, ...productAccessFilter(session.userId) },
      select: { id: true },
    })
    if (product) redirect(`/products/${user.active_product_id}/solo`)
  }

  const products = await prisma.product.findMany({
    where: { archived: false, ...productAccessFilter(session.userId) },
    orderBy: { created_at: 'desc' },
    select: { id: true, name: true, description: true },
  })

  return <ProductPicker products={products} />
}
