/**
 * POST /api/share/space/[token]/verify — Verify an OTP code for a space share link.
 * On success sets a short-lived signed httpOnly cookie so GET can serve the space.
 * Body: { email, code }. Mirrors app/api/share/[token]/verify.
 */

import { createHmac } from 'node:crypto';
import { verifySpaceShareLink, verifyOtpForSpaceShareLink } from '@/lib/space-acl.js';

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

const COOKIE_MAX_AGE = 600;

function _signCookiePayload(token, email, issuedAt, secret) {
  return createHmac('sha256', secret).update(`${token}:${email.toLowerCase().trim()}:${issuedAt}`).digest('hex');
}

async function _resolveSecret() {
  if (process.env.MADARX_SHARE_LINK_SECRET) return process.env.MADARX_SHARE_LINK_SECRET;
  try {
    const { getSecret } = await import('@/lib/secrets.js');
    const val = await getSecret('MADARX_SHARE_LINK_SECRET', { scope: 'global' });
    if (val) return val;
  } catch { /* fall through */ }
  return process.env.MADARX_MASTER_KEY || 'ephemeral-insecure';
}

export async function POST(req, { params }) {
  try {
    const { token } = await params;

    let body;
    try { body = await req.json(); } catch { return Response.json({ ok: false, error: 'Invalid JSON' }, { status: 400 }); }

    const email = String(body?.email || '').trim().toLowerCase();
    const code = String(body?.code || '').trim();
    if (!email || !email.includes('@')) return Response.json({ ok: false, error: 'Valid email is required' }, { status: 400 });
    if (!/^\d{6}$/.test(code)) return Response.json({ ok: false, error: 'A 6-digit code is required' }, { status: 400 });

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

    const otpResult = verifyOtpForSpaceShareLink(link.id, email, code);
    if (!otpResult.ok) {
      const status = otpResult.reason === 'lockout' ? 429 : 401;
      return Response.json({ ok: false, reason: otpResult.reason }, { status, headers: { 'Cache-Control': 'private, no-store' } });
    }

    const secret = await _resolveSecret();
    const issuedAt = Math.floor(Date.now() / 1000);
    const emailB64 = Buffer.from(email).toString('base64url');
    const sig = _signCookiePayload(token, email, issuedAt, secret);
    const cookieValue = `${emailB64}.${issuedAt}.${sig}`;
    const cookieName = `madarx-space-share-otp-${token}`;

    return Response.json(
      { ok: true },
      {
        status: 200,
        headers: {
          'Cache-Control': 'private, no-store',
          'Set-Cookie': [`${cookieName}=${cookieValue}`, `Max-Age=${COOKIE_MAX_AGE}`, 'HttpOnly', 'SameSite=Lax', 'Path=/'].join('; '),
        },
      }
    );
  } catch (err) {
    console.error('POST /api/share/space/[token]/verify error:', err);
    return Response.json({ ok: false, error: 'Verification failed' }, { status: 500 });
  }
}
