/**
 * ZEN API Route Handler
 *
 * Catch-all Next.js App Router handler for all routes under /zen/api/.
 * Place this file at: app/zen/api/[...path]/route.js
 *
 * All HTTP methods are handled by a single factory. GET additionally
 * supports file streaming responses from the storage endpoint.
 */

import { NextResponse } from 'next/server';
import { routeRequest } from './router.js';
import { apiError, getStatusCode } from './respond.js';
import { buildFileResponse } from './file-response.js';
import { fail } from '@zen/core/shared/logger';

const GENERIC_ERROR_MSG = 'An unexpected error occurred. Please try again later.';

/**
 * Create a Next.js route handler for a given HTTP method.
 *
 * @param {boolean} [serveFiles=false] - When true, file streaming responses are
 *   returned directly instead of being wrapped in JSON. Only GET needs this.
 * @returns {Function} Next.js App Router handler
 */
function makeHandler(serveFiles = false) {
  return async function handler(request, { params }) {
    try {
      const path = (await params).path ?? [];
      const response = await routeRequest(request, path);

      if (serveFiles && response.success && response.file) {
        return buildFileResponse(response.file);
      }

      return NextResponse.json(response, { status: getStatusCode(response) });
    } catch (error) {
      fail(`API error: ${error.message}`);
      return NextResponse.json(
        apiError('Internal Server Error', GENERIC_ERROR_MSG),
        { status: 500 }
      );
    }
  };
}

export const GET    = makeHandler(true);
export const POST   = makeHandler();
export const PUT    = makeHandler();
export const PATCH  = makeHandler();
export const DELETE = makeHandler();
