import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { listTripLabels } from '@/lib/services/expenses';

/**
 * GET /api/v1/expenses/trip-labels?search=palm
 *
 * Returns the distinct trip-label values used in this port, ordered by
 * most-recent expense date. Powers the autocomplete on the expense form
 * + the trip filter on the list page so reps don't end up with
 * "Palm Beach 2026" vs " palm beach 2026 " split across two groups in
 * the PDF export.
 *
 * Permission: `expenses.view` - same gate as the list endpoint.
 */
export const GET = withAuth(
  withPermission('expenses', 'view', async (req, ctx) => {
    try {
      const url = new URL(req.url);
      const search = url.searchParams.get('search') ?? undefined;
      const labels = await listTripLabels(ctx.portId, search);
      return NextResponse.json({ data: labels });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
