/**
 * GET /api/share/space/[token] — Public space share resolution (JSON).
 *
 * Returns the space's CURRENT artifacts (live — future/moved artifacts included).
 * No session required. IP rate limited. Honours the optional email-OTP gate via
 * a signed httpOnly cookie set by POST /api/share/space/[token]/verify.
 */

import {
  verifySpaceShareLink,
  recordSpaceShareLinkAccess,
  listSpaceArtifactsForShare,
} from '@/lib/space-acl.js';
import { checkIpRateLimit } from '@/lib/share-secret.js';
import { requestIp } from '@/lib/compliance-audit.js';
import { createHmac, timingSafeEqual } from 'node:crypto';

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

const COOKIE_MAX_AGE_MS = 600 * 1000;

/** Verifies the signed OTP cookie set by the verify route. Returns email or null. */
export async function verifySpaceOtpCookie(req, token) {
  const cookieName = `madarx-space-share-otp-${token}`;
  const cookieHeader = req?.headers?.get?.('cookie') || '';
  const escapedName = cookieName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const match = cookieHeader.match(new RegExp(`(?:^|;\\s*)${escapedName}=([^;]+)`));
  if (!match) return null;

  const cookieValue = decodeURIComponent(match[1]);
  const parts = cookieValue.split('.');
  if (parts.length < 3) return null;
  const sig = parts[parts.length - 1];
  const issuedAt = parseInt(parts[parts.length - 2], 10);
  const emailB64 = parts.slice(0, parts.length - 2).join('.');
  if (!emailB64 || !issuedAt || !sig) return null;
  if (Date.now() - issuedAt * 1000 > COOKIE_MAX_AGE_MS) return null;

  let email;
  try { email = Buffer.from(emailB64, 'base64url').toString('utf8'); } catch { return null; }
  if (!email || !email.includes('@')) return null;

  let secret = process.env.MADARX_SHARE_LINK_SECRET;
  if (!secret) {
    try {
      const { getSecret } = await import('@/lib/secrets.js');
      secret = await getSecret('MADARX_SHARE_LINK_SECRET', { scope: 'global' });
    } catch { /* fall through */ }
  }
  if (!secret) return null;

  const expected = createHmac('sha256', secret).update(`${token}:${email}:${issuedAt}`).digest('hex');
  const expectedBuf = Buffer.from(expected, 'hex');
  let sigBuf;
  try { sigBuf = Buffer.from(sig, 'hex'); } catch { return null; }
  if (sigBuf.length !== expectedBuf.length) return null;
  if (!timingSafeEqual(expectedBuf, sigBuf)) return null;
  return email;
}

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

  const ip = requestIp(req);
  const rate = checkIpRateLimit(ip);
  if (!rate.ok) {
    const retry = Math.ceil((rate.retryAfterMs || 3600000) / 1000);
    return Response.json(
      { error: 'Too many requests', retry_after_seconds: retry },
      { status: 429, headers: { 'Cache-Control': 'private, no-store', 'Retry-After': String(retry) } }
    );
  }

  const verification = await verifySpaceShareLink(token);
  if (!verification.ok) {
    return Response.json(
      { error: verification.reason },
      { status: verification.status || 410, headers: { 'Cache-Control': 'private, no-store' } }
    );
  }

  const { link, space } = verification;

  if (Boolean(link.require_email_otp)) {
    const verifiedEmail = await verifySpaceOtpCookie(req, token);
    if (!verifiedEmail) {
      return Response.json(
        { status: 'otp_required', otp_endpoint: `/api/share/space/${token}/otp`, verify_endpoint: `/api/share/space/${token}/verify` },
        { status: 401, headers: { 'Cache-Control': 'private, no-store' } }
      );
    }
    recordSpaceShareLinkAccess(link.id, req, verifiedEmail);
  } else {
    recordSpaceShareLinkAccess(link.id, req, null);
  }

  const artifacts = listSpaceArtifactsForShare(space.id);
  return Response.json(
    { ok: true, space: { id: space.id, name: space.name }, artifacts },
    { headers: { 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff' } }
  );
}
