'use server'

import { revalidatePath } from 'next/cache'
import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import { z } from 'zod'
import { prisma } from '@/lib/prisma'
import { SessionData, sessionOptions } from '@/lib/session'
import { productAccessFilter } from '@/lib/product-access'

async function getSession() {
  return getIronSession<SessionData>(await cookies(), sessionOptions)
}

const setSchema = z.object({ productId: z.string().min(1) })

export async function setActiveProductAction(productId: string) {
  const session = await getSession()
  if (!session.userId) return { error: 'Niet ingelogd' }
  if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }

  const parsed = setSchema.safeParse({ productId })
  if (!parsed.success) return { error: 'Ongeldig product-id' }

  const product = await prisma.product.findFirst({
    where: { id: parsed.data.productId, archived: false, ...productAccessFilter(session.userId) },
  })
  if (!product) return { error: 'Product niet gevonden of niet toegankelijk' }

  await prisma.user.update({
    where: { id: session.userId },
    data: { active_product_id: parsed.data.productId },
  })

  revalidatePath('/', 'layout')
  return { success: true, productId: parsed.data.productId }
}

export async function clearActiveProductAction() {
  const session = await getSession()
  if (!session.userId) return { error: 'Niet ingelogd' }
  if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }

  await prisma.user.update({
    where: { id: session.userId },
    data: { active_product_id: null },
  })

  revalidatePath('/', 'layout')
  return { success: true }
}
