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 entries = await prisma.directoryEntry.findMany({
    orderBy: [{ area: 'asc' }, { order: 'asc' }, { name: 'asc' }],
  })

  return NextResponse.json(entries)
}

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 { name, position, area, email, phone, mobile, active, order } = body

  if (!name) return NextResponse.json({ error: 'Nombre requerido' }, { status: 400 })

  const entry = await prisma.directoryEntry.create({
    data: {
      name,
      position: position || null,
      area: area || null,
      email: email || null,
      phone: phone || null,
      mobile: mobile || null,
      active: active ?? true,
      order: order ?? 0,
    },
  })

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