import { NextResponse } from 'next/server';

import { withAuth, withPermission, 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 {
    const q = req.nextUrl.searchParams.get('q');
    if (!q) {
      return NextResponse.json({ data: [] });
    }
    const companies = await autocomplete(ctx.portId, q);
    return NextResponse.json({ data: companies });
  } catch (error) {
    return errorResponse(error);
  }
};

export const GET = withAuth(withPermission('companies', 'view', autocompleteHandler));
