/**
 * POST /api/share/space/[token]/otp — Request an OTP for a space share link.
 * Public. Body: { email }. Mirrors app/api/share/[token]/otp (flood + lockout guards).
 */

import { verifySpaceShareLink, createOtpForSpaceShareLink } from '@/lib/space-acl.js';
import { getDb, nowIso } from '@/lib/db.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(req, { params }) {
  try {
    const { token } = await params;
    const body = await req.json().catch(() => ({}));
    const { email } = body || {};
    if (!email || typeof email !== 'string' || !email.includes('@')) {
      return Response.json({ error: 'Valid email is required' }, { status: 400 });
    }

    const verification = await verifySpaceShareLink(token);
    if (!verification.ok) {
      return Response.json({ error: verification.reason }, { status: verification.status || 410 });
    }
    const { link } = verification;
    if (!link.require_email_otp) {
      return Response.json({ error: 'This share link does not require email verification' }, { status: 400 });
    }

    const db = getDb();
    const normalizedEmail = email.toLowerCase().trim();

    const LOCKOUT_WINDOW_ISO = new Date(Date.now() - 15 * 60 * 1000).toISOString();
    const lockedOut = db
      .prepare(
        `SELECT id, created_at FROM space_share_link_otps
          WHERE share_link_id = ? AND email = ? AND attempts >= 5 AND created_at > ? AND verified_at IS NULL
          ORDER BY created_at DESC LIMIT 1`
      )
      .get(link.id, normalizedEmail, LOCKOUT_WINDOW_ISO);
    if (lockedOut) {
      const lockoutEndsAt = new Date(lockedOut.created_at).getTime() + 15 * 60 * 1000;
      const retryAfter = Math.max(0, Math.ceil((lockoutEndsAt - Date.now()) / 1000));
      return Response.json({ ok: false, reason: 'lockout', retry_after: retryAfter }, { status: 429 });
    }

    const existing = db
      .prepare(
        `SELECT id, expires_at, attempts FROM space_share_link_otps
          WHERE share_link_id = ? AND email = ? AND expires_at > ? AND verified_at IS NULL
          ORDER BY created_at DESC LIMIT 1`
      )
      .get(link.id, normalizedEmail, nowIso());
    if (existing && existing.attempts < 5) {
      const remainingSec = Math.max(0, Math.ceil((new Date(existing.expires_at).getTime() - Date.now()) / 1000));
      return Response.json({ ok: true, expires_in: remainingSec, message: 'A verification code was already sent to this address. Check your inbox.' });
    }

    const result = await createOtpForSpaceShareLink(link.id, normalizedEmail);
    if (!result.ok) return Response.json({ error: result.error || 'Failed to create OTP' }, { status: 400 });

    return Response.json({
      ok: true,
      expires_in: result.expires_in,
      ...(result.email_sent === false ? { warning: 'Verification email could not be sent. Contact the link owner.' } : {}),
    });
  } catch (err) {
    if (err?.status) return Response.json({ error: err.error || 'error' }, { status: err.status });
    console.error('POST /api/share/space/[token]/otp error:', err);
    return Response.json({ error: 'Failed to send verification code' }, { status: 500 });
  }
}
