import { NextRequest, NextResponse } from 'next/server'
import { getSessionUser, unauthorized, forbidden } from '@/lib/sessionUser'
import { prisma } from '@/lib/prisma'

export async function PUT(req: NextRequest, { params }: { params: { id: string } }) {
  const u = await getSessionUser()
  if (!u) return unauthorized()
  if (!u.canEdit) return forbidden()

  const id = parseInt(params.id)
  const body = await req.json()
  const { title, content, published } = body

  const news = await prisma.news.update({
    where: { id },
    data: { title, content, published: published ?? false },
  })

  await prisma.auditLog.create({
    data: { userId: u.userId, action: 'UPDATE_NEWS', entity: 'News', entityId: id },
  })

  return NextResponse.json(news)
}

export async function DELETE(_req: NextRequest, { params }: { params: { id: string } }) {
  const u = await getSessionUser()
  if (!u) return unauthorized()
  if (!u.canEdit) return forbidden()

  const id = parseInt(params.id)
  const news = await prisma.news.findUnique({ where: { id } })
  if (!news) return NextResponse.json({ error: 'No encontrado' }, { status: 404 })

  await prisma.news.delete({ where: { id } })

  await prisma.auditLog.create({
    data: { userId: u.userId, action: 'DELETE_NEWS', entity: 'News', entityId: id, details: news.title },
  })

  return NextResponse.json({ ok: true })
}
