/**
 * Chat API proxy route handlers for Next.js App Router.
 *
 * Usage in a site/template:
 *   // app/api/chat/route.ts
 *   export { GET, POST } from 'keystone-design-bootstrap/next/routes/chat';
 *
 * Supports both anonymous (session-based) and authenticated (contact-driven) flows.
 * Both flows hit the same backend endpoint (`/public/messages`); the discriminator
 * is whether `identifier` (session string) or `contact_id` (integer) is supplied.
 *
 * Env (server-side only):
 * - API_URL (default: http://localhost:3000/api/v1)
 * - API_KEY
 */

// IMPORTANT:
// Do NOT import NextRequest/NextResponse here.
// When `keystone-design-bootstrap` is used as a local file dependency, it may have its own
// `next` installation under its own `node_modules`, which causes type identity conflicts
// for route handlers. Instead, export a factory so the consuming app can pass in its
// own `NextResponse` (from its own `next/server`) while we keep the core logic shared.

import { clientContextHeaders } from './proxy-headers';

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 createChatRouteHandlers(deps?: { NextResponse?: { json: JsonResponder } }) {
  const json: JsonResponder = deps?.NextResponse?.json ?? ((body, init) => Response.json(body, init));

  return {
    // POST /api/chat — send a message (session-based or contact-driven)
    POST: async (request: Request): Promise<Response> => {
      try {
        const body = await request.json();
        const { identifier, contact_id, body: messageBody, display_name, page_url } = body;

        if (!messageBody) {
          return json({ success: false, error: 'Message body is required.' }, { status: 400 });
        }
        if (!identifier && !contact_id) {
          return json(
            { success: false, error: 'identifier or contact_id is required.' },
            { status: 400 }
          );
        }

        const response = await fetch(`${API_URL}/public/messages`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-API-Key': API_KEY,
            ...clientContextHeaders(request),
          },
          body: JSON.stringify({ identifier, contact_id, body: messageBody, display_name, page_url }),
        });

        const data = await response.json();
        if (!response.ok) {
          return json(
            { success: false, error: data.error || 'Failed to send message. Please try again.' },
            { status: response.status }
          );
        }
        return json({ success: true, data: data.data });
      } catch (error) {
        console.error('Chat message error:', error);
        return json({ success: false, error: 'Network error. Please try again later.' }, { status: 500 });
      }
    },

    // GET /api/chat?identifier=... or ?contact_id=... — load message history
    GET: async (request: Request): Promise<Response> => {
      try {
        const { searchParams } = new URL(request.url);
        const identifier = searchParams.get('identifier');
        const contactId = searchParams.get('contact_id');

        if (!identifier && !contactId) {
          return json({ success: false, error: 'identifier or contact_id is required.' }, { status: 400 });
        }

        const query = contactId
          ? `contact_id=${encodeURIComponent(contactId)}`
          : `identifier=${encodeURIComponent(identifier!)}`;

        const response = await fetch(`${API_URL}/public/messages?${query}`, {
          headers: { 'X-API-Key': API_KEY },
        });

        const data = await response.json();
        if (!response.ok) {
          return json(
            { success: false, error: data.error || 'Failed to load messages.' },
            { status: response.status }
          );
        }
        return json({ success: true, data: data.data || [] });
      } catch (error) {
        console.error('Chat history error:', error);
        return json({ success: false, error: 'Network error. Please try again later.' }, { status: 500 });
      }
    },
  };
}
