import 'server-only'

import { NextRequest, NextResponse } from 'next/server'
import { getSessionUser } from '@/lib/auth'
import { contextForAccount, mayOpenContext, type PageContext } from '@/lib/page-context'
import { isPhotoSide, putUnitPhoto, removeUnitPhoto } from '@/lib/data/pilot-units'

/**
 * Unit side-photo handlers shared by the Pilot Dispatch Dashboard
 * (/api/pd/unit-photos) and the Pilot Car Driver app (/api/pc/unit-photos).
 * Each route keeps its own path and its own page context; the photos belong
 * to the signed-in account either way, and every change is logged with the
 * person's name.
 */
export function unitPhotoRoutes(context: PageContext) {
  async function guard() {
    const user = await getSessionUser()
    if (!user) return { error: NextResponse.json({ error: 'Sign in first.' }, { status: 401 }) }
    if (!mayOpenContext(context, contextForAccount(user.role), user.internal)) {
      return { error: NextResponse.json({ error: 'Unit photos are managed from your own dashboard.' }, { status: 403 }) }
    }
    return { user }
  }
  return {
    async POST(req: NextRequest) {
      const g = await guard()
      if ('error' in g) return g.error
      const form = await req.formData()
      const unitId = String(form.get('unit_id') ?? '').trim().slice(0, 80)
      const side = form.get('side')
      const file = form.get('file')
      if (!unitId || !isPhotoSide(side) || !(file instanceof File)) return NextResponse.json({ error: 'Unit, side and an image are required.' }, { status: 400 })
      const r = await putUnitPhoto({ ownerUserId: g.user.id, unitId, side, file, actor: { id: g.user.id, label: g.user.name || g.user.email } })
      return r.ok ? NextResponse.json(r) : NextResponse.json({ error: r.error }, { status: 400 })
    },
    async DELETE(req: NextRequest) {
      const g = await guard()
      if ('error' in g) return g.error
      const body = await req.json().catch(() => ({}))
      const unitId = String(body.unit_id ?? '').trim().slice(0, 80)
      const side = body.side
      if (!unitId || !isPhotoSide(side)) return NextResponse.json({ error: 'Unit and side are required.' }, { status: 400 })
      const r = await removeUnitPhoto({ ownerUserId: g.user.id, unitId, side, actor: { id: g.user.id, label: g.user.name || g.user.email } })
      return r.ok ? NextResponse.json(r) : NextResponse.json({ error: r.error }, { status: 400 })
    },
  }
}
