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

import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { search, saveRecentSearch } from '@/lib/services/search.service';
import { searchQuerySchema } from '@/lib/validators/search';

export const GET = withAuth(async (req: NextRequest, ctx) => {
  try {
    const q = req.nextUrl.searchParams.get('q') ?? '';

    if (q.length < 2) {
      return NextResponse.json({ clients: [], interests: [], berths: [] });
    }

    // Validate via schema (also enforces max length)
    searchQuerySchema.parse({ q });

    const results = await search(ctx.portId, q);

    // Fire-and-forget — do not await
    saveRecentSearch(ctx.userId, ctx.portId, q);

    return NextResponse.json(results);
  } catch (error) {
    return errorResponse(error);
  }
});
