import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { testConnection } from '@/lib/services/umami.service';

/**
 * POST /api/v1/admin/umami/test - admin-only Umami connection check.
 *
 * Returns `{ data: { ok: true, visitors } }` on success or
 * `{ data: { ok: false, error } }` on failure. Mirrors the shape used by
 * the Documenso health endpoint so the existing test-button UI pattern
 * just works.
 */
export const POST = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx) => {
    try {
      const result = await testConnection(ctx.portId);
      return NextResponse.json({ data: result });
    } catch (err) {
      const error = err instanceof Error ? err.message : 'Unknown error';
      return NextResponse.json({ data: { ok: false, error } });
    }
  }),
);
