// tdd-guard:skip — thin Next.js route handler (auth gate + single update);
// permission behaviour covered by the admin route permission-gate tests.
import { NextRequest, NextResponse } from 'next/server'
import { getUserSession } from '@/lib/auth/permissions'
import { isAtLeastRole } from '@/lib/auth/permissions-shared'
import { apiError } from '@/lib/api/error'
import { RetryEmailBody } from '@/lib/api/schemas'
import { checkCsrf } from '@/lib/security'
import { createClient } from '@/lib/supabase/server'

export async function POST(request: NextRequest) {
  const csrf = checkCsrf(request); if (csrf) return csrf
  const session = await getUserSession()
  if (!session) return apiError.unauthorized()
  if (!isAtLeastRole(session, 'admin')) return apiError.forbidden()

  const parsed = RetryEmailBody.safeParse(await request.json().catch(() => ({})))
  if (!parsed.success) return apiError.invalidBody(parsed.error.issues)
  const { id } = parsed.data

  const supabase = await createClient()

  // KAR-771: never select template_data (holds the recovery link). Explicit
  // safe columns — authenticated has no SELECT on template_data after the
  // email-queue-protect migration.
  const { data: updated, error } = await supabase
    .from('email_queue')
    .update({ status: 'pending', error: null })
    .eq('id', id)
    .select('id, to_email, template, status, created_at, sent_at, error, is_demo')
    .single()

  if (error) {
    return NextResponse.json({ error: error.message }, { status: 500 })
  }

  return NextResponse.json({ entry: updated })
}
