/**
 * Re-authentication route — session-security (wave-13).
 * Mounted at /api/reauth.
 *
 * POST / → verify user's current password (re-auth for sensitive actions).
 *          Returns 200 { ok: true } on success, 401 on wrong password.
 *          Uses timing-safe comparison — never === for credentials.
 */
import { Hono } from 'hono'
import { z } from 'zod'
import type { AppEnv } from '../types'
import { authMiddleware } from '../middleware/auth'
import { verifyPassword } from '@zync/auth'
import { withDoHash } from '../lib/password-hash-do'
import { findUserById } from '@zync/db/queries'

export const reauthRoute = new Hono<AppEnv>()

reauthRoute.use('*', authMiddleware)

const reauthBodySchema = z.object({
  password: z.string().min(1),
})

reauthRoute.post('/', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user') {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const body = await c.req.json().catch(() => null)
  const parsed = reauthBodySchema.safeParse(body)
  if (!parsed.success) {
    return c.json({ error: 'Validation failed', issues: parsed.error.issues }, 400)
  }

  const db = c.get('db')
  const user = await findUserById(db, session.sub)
  if (!user || !user.passwordHash) {
    // User not found or no password (OAuth-only account).
    return c.json({ error: 'Re-authentication not available' }, 400)
  }

  // Timing-safe password verification — never === for credentials.
  const valid = await verifyPassword(parsed.data.password, user.passwordHash, withDoHash(c.env))
  if (!valid) {
    return c.json({ error: 'Invalid password' }, 401)
  }

  return c.json({ ok: true }, 200)
})
