import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSessionUser } from '@/lib/auth'
import { acceptableRoles, respondToRule, toViews } from '@/lib/data/auto-participant-rules'

const schema = z.object({
  rule_id: z.string().uuid().optional(),
  token: z.string().min(16).max(200).optional(),
  decision: z.enum(['accept', 'decline', 'stop']),
  role_type: z.string().optional().nullable(),
})

/**
 * Accept / decline a request addressed to me, or stop being included (Task
 * 6.4, D4, D6, D16). The signed-in email must match the rule's email.
 */
export async function POST(req: NextRequest) {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: 'Sign in first.' }, { status: 401 })
  const parsed = schema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success || (!parsed.data.rule_id && !parsed.data.token)) return NextResponse.json({ error: 'Invalid request.' }, { status: 400 })
  const res = await respondToRule({ user, ruleId: parsed.data.rule_id, token: parsed.data.token, decision: parsed.data.decision, role_type: parsed.data.role_type })
  if (!res.ok) {
    const needsRole = res.status === 400 && /which of your roles/i.test(res.error) ? await acceptableRoles(user.id) : undefined
    return NextResponse.json({ error: res.error, ...(needsRole ? { needs_role: needsRole } : {}) }, { status: res.status ?? 400 })
  }
  const [view] = await toViews([res.rule])
  return NextResponse.json({ ok: true, rule: view })
}
