import { NextResponse } from 'next/server';

import { withAuth } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { listSettings } from '@/lib/services/settings.service';
import { resolveVocabulary, VOCABULARIES, type VocabularyKey } from '@/lib/vocabularies';

/**
 * GET /api/v1/vocabularies
 *
 * Returns the resolved per-port vocabulary lists (admin overrides
 * merged with shipped defaults). Any authenticated user in this port
 * can read - vocabularies drive in-app pickers (status reasons,
 * interest temperatures, expense categories, etc.) so reps need read
 * access without holding `admin.manage_settings`.
 *
 * Edits still go through `/api/v1/admin/settings` (admin-only).
 */
export const GET = withAuth(async (_req, ctx) => {
  try {
    const { portSettings } = await listSettings(ctx.portId);
    const overridesByKey = new Map<string, unknown>();
    for (const row of portSettings) overridesByKey.set(row.key, row.value);

    const data: Record<string, readonly string[]> = {};
    for (const def of VOCABULARIES) {
      data[def.key] = resolveVocabulary(def.key as VocabularyKey, overridesByKey.get(def.key));
    }
    return NextResponse.json({ data });
  } catch (error) {
    return errorResponse(error);
  }
});
