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

export async function GET() {
  const u = await getSessionUser()
  if (!u) return unauthorized()

  const news = await prisma.news.findMany({
    orderBy: { createdAt: 'desc' },
    include: { author: { select: { name: true, email: true } } },
  })

  return NextResponse.json(news)
}

export async function POST(req: NextRequest) {
  const u = await getSessionUser()
  if (!u) return unauthorized()
  if (!u.canEdit) return forbidden()

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

  if (!title || !content) return NextResponse.json({ error: 'Título y contenido requeridos' }, { status: 400 })

  const news = await prisma.news.create({
    data: { title, content, published: published ?? false, authorId: u.userId },
    include: { author: { select: { name: true } } },
  })

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

  return NextResponse.json(news, { status: 201 })
}
