import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { listTemplates } from '@/lib/services/documenso-client';

/**
 * GET /api/v1/admin/documenso/templates
 *
 * Lists every Documenso template visible to the configured API key
 * for the calling port. Drives the "Documenso-first templates" admin
 * picker (R62) - reps see real template names instead of having to
 * type numeric IDs.
 *
 * Gated on `admin.manage_settings` since the data exposed is essentially
 * the same surface area as the Documenso settings page itself.
 *
 * Response shape: `{ data: Array<{ id, name }> }`. Cached client-side
 * by the picker for ~5 minutes.
 */
export const GET = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx) => {
    try {
      const templates = await listTemplates(ctx.portId);
      return NextResponse.json({ data: templates });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
