import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSessionUser } from '@/lib/auth'
import { decideRemoval } from '@/lib/domain/modes'
import { companyAdminCount, loadUserContexts } from '@/lib/data/modes'

/** What removing this role would cost, so the confirmation can say it plainly (§20). */
export async function POST(req: NextRequest) {
  const user = await getSessionUser()
  if (!user) return NextResponse.json({ error: 'Sign in first.' }, { status: 401 })
  const parsed = z.object({ key: z.string().min(1).max(120) }).safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) return NextResponse.json({ error: 'Check the request.' }, { status: 400 })
  const contexts = await loadUserContexts(user)
  const target = contexts.find((c) => c.key === parsed.data.key)
  if (!target) return NextResponse.json({ error: 'That workspace is not on your account.' }, { status: 404 })
  const count = target.companyId ? await companyAdminCount(target.companyId) : 0
  const d = decideRemoval({ contexts, key: parsed.data.key, companyAdminCount: count })
  return d.ok ? NextResponse.json({ ok: true, warning: d.warning }) : NextResponse.json({ error: d.reason }, { status: 400 })
}
