// tdd-guard:skip — Next.js route handler; auth/role gating is exercised by the
// admin permission-gates tests, the unlink is a single scoped update.
import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getUserSession } from '@/lib/auth/permissions'
import { checkCsrf } from '@/lib/security'
import { createClient } from '@/lib/supabase/server'
import { routeError } from '@/lib/api/error'

// KAR-787 / R51: unlink a user account from its consultant (Mitarbeiter) record.
// Sets consultants.auth_user_id = NULL for the consultant currently linked to
// the user's auth account. Admin/Masteradmin only.
const UnlinkBodySchema = z.object({
  userId: z.string().uuid(),
})

export async function POST(request: NextRequest) {
  const csrf = checkCsrf(request); if (csrf) return csrf
  const session = await getUserSession()
  if (!session) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }
  if (session.role !== 'admin' && session.role !== 'masteradmin') {
    return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
  }

  const parsed = UnlinkBodySchema.safeParse(await request.json().catch(() => ({})))
  if (!parsed.success) {
    return NextResponse.json({ error: 'Invalid body', issues: parsed.error.issues }, { status: 400 })
  }
  const { userId } = parsed.data

  const supabase = await createClient()

  const { data: profile } = await supabase
    .from('user_profiles')
    .select('auth_user_id')
    .eq('id', userId)
    .single()
  if (!profile?.auth_user_id) {
    return NextResponse.json({ error: 'User not found or has no auth account' }, { status: 404 })
  }

  const { data: unlinked, error: unlinkError } = await supabase
    .from('consultants')
    .update({ auth_user_id: null })
    .eq('auth_user_id', profile.auth_user_id)
    .select('id')

  if (unlinkError) {
    return routeError('Verknüpfung konnte nicht gelöst werden.', unlinkError)
  }

  await supabase.from('user_audit_log').insert({
    actor_id:       session.authUserId,
    target_user_id: userId,
    action:         'user.consultant_unlinked',
    details:        { consultant_ids: (unlinked ?? []).map((c) => c.id) },
  })

  return NextResponse.json({ ok: true, unlinked: (unlinked ?? []).length })
}
