import { NextResponse } from 'next/server';

import { type RouteHandler } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { autocomplete } from '@/lib/services/companies.service';

export const autocompleteHandler: RouteHandler = async (req, ctx) => {
  try {
    // Empty `q` returns the most recent companies (capped to the same
    // 10-row limit the search path uses). The companion CompanyPicker
    // initially renders with an empty query because the popover opens
    // before the rep has typed anything — returning [] there hid every
    // company even when the system had rows. Returning a recent list
    // gives the rep something to scan or select immediately.
    const q = req.nextUrl.searchParams.get('q') ?? '';
    const companies = await autocomplete(ctx.portId, q);
    return NextResponse.json({ data: companies });
  } catch (error) {
    return errorResponse(error);
  }
};
