// tdd-guard:skip — thin wrapper around Supabase admin generateLink; the secure
// behaviour (no cleartext password) is exercised via the invite/reset route flows.
//
// Server-only — never import this in client components. Uses the service-role
// admin client (see docs/foundation/service-role-intent-register.md).
import { createAdminClient } from '@/lib/supabase/admin'
import { logger } from '@/lib/logger'

/**
 * Generates a single-use recovery link for an existing auth user, pointing at
 * our own `/auth/confirm` page rather than Supabase's GET verify endpoint.
 *
 * Why not the default `action_link`: that link hits `/auth/v1/verify` which
 * consumes the one-time OTP on the first GET. Enterprise mail-security
 * (Defender/SafeLinks etc.) and chat link-previews PREFETCH links, so the token
 * would be spent before the real recipient clicks (KAR-772). Instead we hand
 * out the `token_hash` and let `/auth/confirm` redeem it via `verifyOtp` on an
 * explicit user click — a prefetch just renders the page.
 *
 * Still no cleartext password is generated, stored, transmitted, or displayed
 * (KAR-769 / D3). The link is delivered via the email_queue.
 *
 * @param email  the auth user's email
 * @param origin absolute origin of the app (e.g. https://app.kaiis.de)
 * @param next   safe relative path to land on after confirmation
 *               (e.g. `/auth/change-password` or `/reset-password`)
 * @returns the confirm link, or null if generation failed
 */
export async function generateRecoveryLink(
  email: string,
  origin: string,
  next: string
): Promise<string | null> {
  const admin = createAdminClient()
  const { data, error } = await admin.auth.admin.generateLink({
    type: 'recovery',
    email,
    // redirectTo is unused by our token_hash flow, but pass an allowlisted URL
    // so Supabase doesn't fall back to a stale Site URL when building metadata.
    options: { redirectTo: `${origin}/auth/confirm` },
  })

  if (error || !data?.properties?.hashed_token) {
    // Log domain only — never the email or the link (ASVS V13.9.1 / V14.x).
    logger.error('auth.recovery_link.generate_failed', error, {
      to_email_domain: email.split('@')[1] ?? 'unknown',
    })
    return null
  }

  const url = new URL('/auth/confirm', origin)
  url.searchParams.set('token_hash', data.properties.hashed_token)
  url.searchParams.set('type', 'recovery')
  url.searchParams.set('next', next)
  return url.toString()
}
