import { getSession } from '@/lib/session'
import { isAdmin } from '@/lib/admin'
import { deleteNews, updateNews } from '@/lib/admin-news'

export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession()
  if (!(await isAdmin(session))) return Response.json({ success: false, error: 'forbidden' }, { status: 403 })
  const { id } = await params
  await deleteNews(Number(id))
  return Response.json({ success: true })
}

export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession()
  if (!(await isAdmin(session))) return Response.json({ success: false, error: 'forbidden' }, { status: 403 })
  const { id } = await params
  let b: Record<string, string> = {}
  try { b = await request.json() } catch { return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 }) }
  const titulo = String(b.titulo ?? '').trim()
  const contenido = String(b.contenido ?? '').trim()
  const enlace = String(b.enlace ?? '').trim() || null
  const tituloEn = String(b.tituloEn ?? '').trim() || null
  const contenidoEn = String(b.contenidoEn ?? '').trim() || null
  if (!titulo || !contenido) return Response.json({ success: false, error: 'emptyError' })
  await updateNews(Number(id), titulo, contenido, enlace, tituloEn, contenidoEn)
  return Response.json({ success: true })
}
