import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'

import { SessionData, sessionOptions } from '@/lib/session'
import { prisma } from '@/lib/prisma'
import { productAccessFilter } from '@/lib/product-access'
import { ideaToDto } from '@/lib/idea-dto'
import { IdeaList } from '@/components/ideas/idea-list'

export const dynamic = 'force-dynamic'

export default async function IdeasPage() {
  const session = await getIronSession<SessionData>(await cookies(), sessionOptions)

  // M12: idee is strikt user_id-only (geen productAccessFilter — Q8).
  const ideas = await prisma.idea.findMany({
    where: { user_id: session.userId, archived: false },
    orderBy: { created_at: 'desc' },
    include: {
      product: { select: { id: true, name: true, repo_url: true } },
      secondary_products: { include: { product: { select: { id: true, name: true } } } },
    },
    take: 200,
  })

  // Productenlijst voor de filter-dropdown + voor "Nieuw idee"-form.
  // Producten zijn product-scoped (kan team-shared zijn) — productAccessFilter
  // is hier dus wél juist.
  const products = await prisma.product.findMany({
    where: { ...productAccessFilter(session.userId), archived: false },
    orderBy: { name: 'asc' },
    select: { id: true, name: true, repo_url: true },
  })

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

  const activeProductId =
    user?.active_product_id && products.some((p) => p.id === user.active_product_id)
      ? user.active_product_id
      : null

  return (
    <div className="p-6 max-w-5xl mx-auto w-full">
      <header className="mb-6 flex items-baseline justify-between">
        <h1 className="text-xl font-medium text-foreground">Ideeën</h1>
        <p className="text-sm text-muted-foreground">
          Lichtgewicht voorstellen die je via Grill Me en Make Plan tot een PBI laat groeien.
        </p>
      </header>

      <IdeaList
        ideas={ideas.map((i) => ideaToDto(i))}
        products={products}
        isDemo={session.isDemo ?? false}
        activeProductId={activeProductId}
      />
    </div>
  )
}
