import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { requireAdmin } from '@/lib/auth-helpers'
import { MOCK_UNITS } from '@/lib/mock'
import { UnitSchema } from '@/lib/validations'

const USE_MOCK = process.env.USE_MOCK === 'true'

export async function GET() {
  try {
    const data = USE_MOCK
      ? MOCK_UNITS
      : await prisma.unit.findMany({ where: { deletedAt: null }, orderBy: { order: 'asc' } })
    return NextResponse.json({ data })
  } catch {
    return NextResponse.json({ error: 'Server error' }, { status: 500 })
  }
}

export async function POST(req: NextRequest) {
  try {
    await requireAdmin()
    const body = await req.json()
    const parsed = UnitSchema.safeParse(body)
    if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
    const record = await prisma.unit.create({ data: parsed.data })
    return NextResponse.json({ data: record }, { status: 201 })
  } catch {
    return NextResponse.json({ error: 'Server error' }, { status: 500 })
  }
}
