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

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { issueToken } from '@/lib/services/supplemental-forms.service';
import { sendEmail } from '@/lib/email';
import { env } from '@/lib/env';
import { getPortEmailConfig } from '@/lib/services/port-config';

/**
 * POST /api/v1/interests/[id]/supplemental-info-request
 *
 * Auth: requires `interests.edit` so any rep working the deal can fire it.
 * Generates a one-shot token + emails the client the public form URL.
 */
export const POST = withAuth(
  withPermission('interests', 'edit', async (req: NextRequest, ctx, params) => {
    try {
      const interestId = params.id as string;
      // Two-step UX: rep can generate a link without firing the email
      // (so they can copy + share manually through WhatsApp etc.), then
      // come back and send the templated email separately. Default stays
      // `true` for back-compat. The body is optional — older callers
      // POST with no body and still trigger the email.
      let shouldSendEmail = true;
      try {
        const body = (await req.clone().json()) as { sendEmail?: boolean };
        if (typeof body?.sendEmail === 'boolean') shouldSendEmail = body.sendEmail;
      } catch {
        // No JSON body — keep the default.
      }

      const result = await issueToken({
        interestId,
        portId: ctx.portId,
        issuedBy: ctx.userId,
      });

      // §1.4: prefer the per-port supplemental_form_url (typically the
      // marketing site's hosted form) when configured; otherwise fall
      // back to the built-in CRM route. Both modes use the same token
      // — the marketing site forwards the token to the same backend.
      const emailCfg = await getPortEmailConfig(ctx.portId);
      const link = emailCfg.supplementalFormUrl
        ? `${emailCfg.supplementalFormUrl}?token=${encodeURIComponent(result.token)}`
        : `${env.NEXT_PUBLIC_APP_URL}/public/supplemental-info/${result.token}`;

      if (shouldSendEmail && result.clientEmail) {
        const html = `
          <p>Hello ${escapeHtml(result.clientName)},</p>
          <p>Before we draft your Expression of Interest, we need to confirm a few details.
            The form below is pre-filled with what we have on file — please review, correct
            anything that's wrong, and add what's missing.</p>
          <p style="text-align:center;margin:24px 0">
            <a href="${link}"
               style="background:#1e3a8a;color:#fff;text-decoration:none;padding:12px 24px;border-radius:6px;display:inline-block">
              Open the form
            </a>
          </p>
          <p style="color:#64748b;font-size:12px">
            This link expires on ${result.expiresAt.toUTCString()}.
            If you didn't expect this email, please let us know.
          </p>
        `;
        await sendEmail(
          result.clientEmail,
          'Please complete a few details before we draft your EOI',
          html,
          undefined,
          undefined,
          ctx.portId,
        );
      }

      return NextResponse.json({
        data: {
          link,
          expiresAt: result.expiresAt.toISOString(),
          emailSent: shouldSendEmail && !!result.clientEmail,
        },
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

function escapeHtml(s: string): string {
  return s
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}
