/**
 * Form submission proxy route handler for Next.js App Router.
 *
 * Usage in a site/template:
 *   // app/api/form/route.ts
 *   export { POST } from 'keystone-design-bootstrap/next/routes/form';
 *
 * Env (server-side only):
 * - API_URL (default: http://localhost:3000/api/v1)
 * - API_KEY
 */

// IMPORTANT:
// Do NOT import NextRequest/NextResponse here.
// Export a factory so the consuming app can pass its own `NextResponse` (from its own
// `next/server`) to avoid type identity conflicts when used as a local file dependency.

const API_URL = process.env.API_URL || 'http://localhost:3000/api/v1';
const API_KEY = process.env.API_KEY || '';

type JsonResponder = (body: unknown, init?: ResponseInit) => Response;

export function createFormRouteHandlers(deps?: { NextResponse?: { json: JsonResponder } }) {
  const json: JsonResponder = deps?.NextResponse?.json ?? ((body, init) => Response.json(body, init));

  return {
    POST: async (request: Request): Promise<Response> => {
      try {
        const body = await request.json();
        const formType = body?.formType;

        if (!formType) {
          return json({ success: false, error: 'Form type is required.' }, { status: 400 });
        }

        const response = await fetch(`${API_URL}/public/form_submissions`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-API-Key': API_KEY,
          },
          body: JSON.stringify(body),
        });

        const data = await response.json();

        if (!response.ok) {
          return json(
            {
              success: false,
              error: data.error || 'Failed to submit form. Please try again.',
            },
            { status: response.status }
          );
        }

        const payload: { success: true; message?: string; eventId?: string } = {
          success: true,
          message: data.message || 'Form submitted successfully.',
        };

        if (formType === 'lead' && data.data?.event_id) {
          payload.eventId = data.data.event_id;
        }

        return json(payload);
      } catch (error) {
        console.error('Form submission error:', error);
        return json(
          {
            success: false,
            error: 'Network error. Please try again later.',
          },
          { status: 500 }
        );
      }
    },
  };
}

