/**
 * POST /api/connectors/[id]/test
 *
 * Thin HTTP wrapper around lib/connectors/test-runner. All probe logic
 * lives in the lib so server-side callers (Login Status) can use it
 * without bouncing through this route (which would hit auth middleware).
 */

import { NextResponse } from 'next/server';
import { runConnectorTest } from '@/lib/connectors/test-runner';
import { setCachedResult } from '@/lib/auth/login-status';

export async function POST(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  try {
    const r = await runConnectorTest(id);
    const { code, ...body } = r;
    // Mirror the fresh probe into the login-status cache so the panel
    // doesn't keep showing a stale 401 after the user fixed the token.
    // Test button = manual user-triggered probe of the same auth surface
    // Login Status renders, so they should agree.
    try {
      setCachedResult(`connector:${id}`, {
        ok: !!body.ok,
        message: body.ok ? (body.message || 'ok') : (body.error || `HTTP ${body.status || '?'}`),
        landed_url: body.url,
        checked_at: Date.now(),
        duration_ms: body.duration_ms ?? 0,
      });
    } catch { /* best-effort; cache write failure shouldn't fail the Test response */ }
    return NextResponse.json(body, code ? { status: code } : undefined);
  } catch (e) {
    // Belt-and-suspenders: never let an uncaught exception bubble to
    // Next's HTML 500 page — the browser would then choke on JSON parse.
    return NextResponse.json(
      { ok: false, error: `internal error: ${(e as Error).message}` },
      { status: 500 },
    );
  }
}
