/**
 * 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';
 *
 * 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.

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: async (request: Request): Promise<Response> => {
      try {
        const body = await request.json();
        const { identifier, body: messageBody, display_name, page_url } = body;

        if (!identifier || !messageBody) {
          return json(
            { success: false, error: 'Identifier and message body are required.' },
            { status: 400 }
          );
        }

        const response = await fetch(`${API_URL}/public/messages`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-API-Key': API_KEY,
          },
          body: JSON.stringify({
            identifier,
            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: async (request: Request): Promise<Response> => {
      try {
        const { searchParams } = new URL(request.url);
        const identifier = searchParams.get('identifier');

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

        const response = await fetch(
          `${API_URL}/public/messages?identifier=${encodeURIComponent(identifier)}`,
          {
            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 }
        );
      }
    },
  };
}

