'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'

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

const profileSchema = z.object({
  email: z.string().trim().email('Ongeldig e-mailadres').max(254).optional(),
  bio: z.string().max(160).optional(),
  bio_detail: z.string().max(2000).optional(),
})

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

  const parsed = profileSchema.safeParse({
    email: (formData.get('email') as string)?.trim() || undefined,
    bio: (formData.get('bio') as string) || undefined,
    bio_detail: (formData.get('bio_detail') as string) || undefined,
  })
  if (!parsed.success) return { error: parsed.error.flatten().fieldErrors }

  try {
    await prisma.user.update({
      where: { id: session.userId },
      data: {
        email: parsed.data.email ?? null,
        bio: parsed.data.bio ?? null,
        bio_detail: parsed.data.bio_detail ?? null,
      },
    })
  } catch (err: unknown) {
    if (
      typeof err === 'object' &&
      err !== null &&
      'code' in err &&
      (err as { code: string }).code === 'P2002'
    ) {
      return { error: 'Dit e-mailadres is al in gebruik' }
    }
    throw err
  }

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