'use server'

import { revalidatePath } from 'next/cache'
import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import { prisma } from '@/lib/prisma'
import { SessionData, sessionOptions } from '@/lib/session'
import { minQuotaPctSchema } from '@/lib/schemas/user'

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

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

  const validRoles = ['PRODUCT_OWNER', 'SCRUM_MASTER', 'DEVELOPER']
  const filtered = roles.filter(r => validRoles.includes(r))
  if (filtered.length === 0) return { error: 'Minimaal één rol is verplicht' }

  await prisma.$transaction([
    prisma.userRole.deleteMany({ where: { user_id: session.userId } }),
    prisma.userRole.createMany({
      data: filtered.map(role => ({ user_id: session.userId, role: role as 'PRODUCT_OWNER' | 'SCRUM_MASTER' | 'DEVELOPER' })),
    }),
  ])

  revalidatePath('/settings')
  return { success: true }
}

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

  const parsed = minQuotaPctSchema.safeParse(value)
  if (!parsed.success) return { error: 'Waarde moet tussen 1 en 100 liggen', status: 422 }

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

  revalidatePath('/settings')
  return { success: true }
}
