import { NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { checkAgentWrite } from '@/lib/agent-auth'
import { buildResultsReport } from '@/lib/report'

export const runtime = 'nodejs'

/**
 * GET — the results email for a graded set, composed server-side.
 *
 * Returns 204 when there is nothing to send: no responses yet, or the email has
 * already gone out. The agent treats 204 as "nothing to do", which is what
 * keeps a re-grade from re-sending.
 */
export async function GET(req: Request) {
  if (!checkAgentWrite(req)) return new NextResponse('Unauthorized', { status: 401 })

  const setId = new URL(req.url).searchParams.get('setId')
  if (!setId) return NextResponse.json({ error: 'setId required' }, { status: 400 })

  const set = await db.itemSet.findUnique({ where: { id: setId } })
  if (!set) return NextResponse.json({ error: 'not found' }, { status: 404 })
  if (set.resultsEmailedAt) return new NextResponse(null, { status: 204 })

  const report = await buildResultsReport(setId)
  if (!report) return new NextResponse(null, { status: 204 })

  return NextResponse.json({
    to: process.env.RESULTS_EMAIL_TO || 'eric.n.tran@gmail.com',
    subject: report.subject,
    body: report.body,
  })
}

/** POST — the agent confirming it sent, so a re-grade does not re-send. */
export async function POST(req: Request) {
  if (!checkAgentWrite(req)) return new NextResponse('Unauthorized', { status: 401 })

  let body: { setId?: string }
  try {
    body = await req.json()
  } catch {
    return new NextResponse('Bad JSON', { status: 400 })
  }
  if (!body.setId) return NextResponse.json({ error: 'setId required' }, { status: 400 })

  try {
    await db.itemSet.update({
      where: { id: body.setId },
      data: { resultsEmailedAt: new Date() },
    })
  } catch {
    return NextResponse.json({ error: 'not found' }, { status: 404 })
  }
  return NextResponse.json({ ok: true })
}
