import { NextRequest, NextResponse } from 'next/server';

// This route proxies DocuSeal directly from Next (server-side), avoiding Lambda.
// It expects server env vars: DOCUSEAL_API_BASE and DOCUSEAL_TOKEN.
// Fallback to DOCUSEAL_PROXY_BASE (Lambda) if direct config is missing.

async function forwardDocuseal(req: NextRequest, ctx: { params: { path: string[] } }) {
  const segments = (ctx.params?.path || []).join('/');

  // Prefer direct DocuSeal upstream
  const dsBase = process.env.DOCUSEAL_API_BASE || process.env.NEXT_PUBLIC_DOCUSEAL_API_BASE || '';
  const dsToken = process.env.DOCUSEAL_TOKEN || process.env.NEXT_PUBLIC_DOCUSEAL_TOKEN || '';

  let upstreamUrl: string | null = null;
  let headers: HeadersInit = { 'Accept': 'application/json' };

  if (dsBase && dsToken) {
    const u = new URL(dsBase.replace(/\/$/, ''));
    u.pathname = `${u.pathname.replace(/\/$/, '')}/${segments}`;
    u.search = req.nextUrl.search;
    upstreamUrl = u.toString();
    headers = { ...headers, 'X-Auth-Token': dsToken };
  } else {
    // Fallback to Lambda proxy if configured
    const proxyBase = process.env.DOCUSEAL_PROXY_BASE || process.env.NEXT_PUBLIC_DOCUSEAL_PROXY_BASE || '';
    if (!proxyBase) {
      return NextResponse.json({ error: 'DocuSeal config missing: set DOCUSEAL_API_BASE + DOCUSEAL_TOKEN' }, { status: 500 });
    }
    const u = new URL(proxyBase.replace(/\/$/, ''));
    u.pathname = `${u.pathname.replace(/\/$/, '')}/${segments}`;
    u.search = req.nextUrl.search;
    upstreamUrl = u.toString();
  }

  try {
    const res = await fetch(upstreamUrl!, { method: 'GET', headers, cache: 'no-store' });
    const contentType = res.headers.get('content-type') || 'application/json; charset=utf-8';
    const text = await res.text();
    return new NextResponse(text, { status: res.status, headers: { 'content-type': contentType } });
  } catch (e: any) {
    return NextResponse.json({ error: 'Upstream error', message: e?.message || String(e) }, { status: 502 });
  }
}

export const GET = forwardDocuseal;
