/**
 * Connector Marketplace API
 *
 *   GET  /api/connectors/marketplace
 *     → { fetched_at, base_url, entries: ConnectorMarketEntry[] }
 *     Pure read — last cached registry merged with installed state.
 *     Returns an empty list when sync has never succeeded.
 *
 *   POST /api/connectors/marketplace
 *     body: { action: 'sync' | 'install' | 'uninstall' | 'update', id?: string }
 *
 *     - sync       refresh registry.json (and installed manifests)
 *     - install    pull manifest + write to <dataDir>/connectors/<id>/
 *     - uninstall  drop manifest (config retained by default)
 *     - update     alias for install when a newer version exists
 *
 * Auth handled by middleware (cookie or X-Forge-Token). All operations
 * are local — secrets never leave the host.
 */

import { NextResponse } from 'next/server';
import {
  listMarketplace,
  syncRegistry,
  installFromRegistry,
} from '@/lib/connectors/sync';
import {
  uninstallConnector,
  getInstalledConnector,
} from '@/lib/connectors/registry';

export async function GET() {
  return NextResponse.json(listMarketplace());
}

export async function POST(req: Request) {
  let body: any = {};
  try { body = await req.json(); } catch {}
  const action = String(body?.action || '').trim();
  const id = body?.id ? String(body.id).trim() : '';

  switch (action) {
    case 'sync': {
      const r = await syncRegistry({ refreshInstalled: !!body?.refreshInstalled });
      return NextResponse.json(r);
    }

    case 'install':
    case 'update': {
      if (!id) return NextResponse.json({ error: 'id is required' }, { status: 400 });
      const r = await installFromRegistry(id);
      if (!r.ok) return NextResponse.json(r, { status: 502 });
      return NextResponse.json(r);
    }

    case 'uninstall': {
      if (!id) return NextResponse.json({ error: 'id is required' }, { status: 400 });
      const keepConfig = body?.keepConfig !== false; // default true
      const ok = uninstallConnector(id, keepConfig);
      if (!ok) return NextResponse.json({ ok: false, error: 'uninstall failed' }, { status: 500 });
      return NextResponse.json({ ok: true });
    }

    case 'status': {
      // Quick "is this id installed and at what version?" probe — used
      // by the UI to refresh a single row without reloading the list.
      if (!id) return NextResponse.json({ error: 'id is required' }, { status: 400 });
      const inst = getInstalledConnector(id);
      return NextResponse.json({
        installed: !!inst,
        installed_version: inst?.installed_version,
        enabled: inst?.enabled ?? false,
      });
    }

    default:
      return NextResponse.json({ error: `unknown action: ${action}` }, { status: 400 });
  }
}
