import { NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { readUploadBytes } from '@/lib/uploads'
import { db } from '@/lib/db'

/**
 * Serves an original handwritten-work photo. Parents see any; a boy sees only
 * his own. Guarded because these are photographs of children's schoolwork on a
 * publicly reachable host.
 */
export async function GET(
  _request: Request,
  { params }: { params: Promise<{ path: string[] }> },
) {
  const session = await getSession()
  if (!session) return new NextResponse('Unauthorized', { status: 401 })

  const { path: segments } = await params
  const relPath = segments.join('/')

  if (session.kind === 'student') {
    const own = await db.response.findMany({
      where: { studentId: session.id },
      select: { imagePaths: true },
    })
    const permitted = own.some(
      (r) => Array.isArray(r.imagePaths) && (r.imagePaths as string[]).includes(relPath),
    )
    if (!permitted) return new NextResponse('Not found', { status: 404 })
  }

  const file = await readUploadBytes(relPath)
  if (!file) return new NextResponse('Not found', { status: 404 })

  return new NextResponse(new Uint8Array(file.buf), {
    headers: {
      'Content-Type': file.mediaType,
      'Cache-Control': 'private, max-age=3600',
    },
  })
}
