import Link from 'next/link'
import { createHash } from 'node:crypto'
import { createAdminClient } from '@/lib/supabase/admin'
import { findEnvUserById } from '@/lib/auth/env-users'
import { findSelfAccountById, selfAccountAsEnvUser } from '@/lib/auth/self-accounts'
import { setAccountContact } from '@/lib/auth/accounts'
import { logSecurityEvent } from '@/lib/security/events'
import { deliveryAfterEmailChange } from '@/lib/domain/account'
import { withinMs } from '@/lib/domain/time'

/**
 * Confirms a new SIGN-IN email (Nash, 2026-09-23): one use, 24-hour link.
 * On success the account row, the profile and (when it only mirrored the old
 * address) the delivery address all move to the new email. Sessions pick the
 * change up live — no sign-out needed.
 */
export default async function VerifyLoginEmailPage({ params }: { params: Promise<{ token: string }> }) {
  const { token } = await params
  const admin = createAdminClient()
  const hash = createHash('sha256').update(token).digest('hex')
  const { data: p } = await admin.from('profiles').select('id, email, delivery_email, pending_login_email, pending_login_email_sent_at').eq('pending_login_email_token_hash', hash).maybeSingle()
  const row = p as { id: string; email: string; delivery_email: string | null; pending_login_email: string | null; pending_login_email_sent_at: string | null } | null
  const fresh = withinMs(row?.pending_login_email_sent_at, 24 * 3_600_000)
  let ok = false
  let error: string | null = null
  if (row?.pending_login_email && fresh) {
    const env = findEnvUserById(row.id) ?? (await findSelfAccountById(row.id).then((s) => (s ? selfAccountAsEnvUser(s) : null)))
    if (!env) error = 'This account no longer exists.'
    else {
      const r = await setAccountContact(env, { email: row.pending_login_email }, 'email verification link')
      if (!r.ok) error = r.error
      else {
        const now = new Date().toISOString()
        const { error: e2 } = await admin.from('profiles').update({
          email: row.pending_login_email, previous_login_email: row.email, login_email_changed_at: now, delivery_email: deliveryAfterEmailChange(row.delivery_email, row.email),
          pending_login_email: null, pending_login_email_token_hash: null, pending_login_email_sent_at: null,
        }).eq('id', row.id)
        ok = !e2
        if (e2) error = e2.message
        await logSecurityEvent({ event: 'account_email_changed', userId: row.id, actorUserId: row.id, actorLabel: env.name || env.email, detail: { from: row.email, to: row.pending_login_email } })
      }
    }
  }
  return (
    <main className="mx-auto max-w-xl px-4 py-10">
      <h1 className="text-2xl font-bold tracking-tight">{ok ? 'Sign-in email changed' : 'This link is not valid or has expired'}</h1>
      <p className="mt-3 text-sm text-neutral-600">
        {ok ? `You now sign in to HeavyHaul Agent with ${row?.pending_login_email}. Your current session keeps working.` : error ?? 'Request a new verification link from your Profile.'}
      </p>
      <p className="mt-4 text-sm"><Link href="/profile" className="font-semibold underline">Back to your Profile</Link></p>
    </main>
  )
}
