import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getEoiTemplateSyncReport } from '@/lib/services/documenso-template-sync.service';

/**
 * GET /api/v1/admin/documenso/sync-template/report
 *
 * Returns the cached sync result from the most recent successful Sync run,
 * so the admin panel's status box survives a page reload without re-hitting
 * Documenso. Returns `{ data: null }` when no sync has run for this port.
 *
 * Admin-only via `admin.manage_settings` - same gate as the sync write
 * endpoint, since the report contains template recipient identities and
 * AcroForm field names that aren't OK to leak outside the admin surface.
 */
export const GET = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx) => {
    try {
      const report = await getEoiTemplateSyncReport(ctx.portId);
      return NextResponse.json({ data: report });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
