// Per-service connection endpoint.
//
// GET    /api/connections/[service]                                       → connection + status + installs[]
// DELETE /api/connections/[service]?scope=global                          → disconnect global install
// DELETE /api/connections/[service]?scope=project&project_id=<id>         → disconnect one project-scoped install
// DELETE /api/connections/[service]?scope=agent&agent_id=<id>             → disconnect one agent-scoped install
// DELETE /api/connections/[service]                                       → defaults to global (back-compat)

import {
  getConnection,
  markConnectionDisconnected,
  credentialNamesFor,
} from '../../../../lib/connections.js';
import {
  listInstances,
  deleteInstance,
  normalizeScopeInput,
} from '../../../../lib/connection-instances.js';
import { summarizeConnection } from '../../../../lib/connection-status.js';
import { deleteSecret } from '../../../../lib/secrets.js';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

export async function GET(_request, context) {
  const params = await Promise.resolve(context.params);
  const service = decodeURIComponent(params.service || '');
  if (!service) return Response.json({ error: 'missing_service' }, { status: 400 });
  const connection = getConnection(service);
  if (!connection) return Response.json({ error: 'not_found' }, { status: 404 });
  return Response.json({
    ok: true,
    connection: {
      ...connection,
      status: summarizeConnection(connection),
      installs: listInstances(service),
    },
  });
}

export async function DELETE(request, context) {
  const params = await Promise.resolve(context.params);
  const service = decodeURIComponent(params.service || '');
  if (!service) return Response.json({ error: 'missing_service' }, { status: 400 });
  const connection = getConnection(service);
  if (!connection) return Response.json({ error: 'not_found' }, { status: 404 });

  const url = new URL(request.url);
  let scopeTuple;
  try {
    scopeTuple = normalizeScopeInput({
      scope: url.searchParams.get('scope'),
      project_id: url.searchParams.get('project_id'),
      agent_id: url.searchParams.get('agent_id'),
    });
  } catch (err) {
    return Response.json({ error: String(err?.message || err) }, { status: 400 });
  }

  // Revoke matching secrets at the targeted scope only.
  const credentialNames = credentialNamesFor(connection);
  const secretOpts = {
    scope: scopeTuple.scope === 'global'
      ? 'global'
      : (scopeTuple.scope === 'project' ? `project:${scopeTuple.project_id}` : `agent:${scopeTuple.agent_id}`),
    project_id: scopeTuple.project_id || undefined,
    agent_id: scopeTuple.agent_id || undefined,
  };
  const revoked = [];
  const skipped = [];
  for (const name of credentialNames) {
    try {
      deleteSecret(name, secretOpts);
      revoked.push(name);
    } catch (err) {
      skipped.push({ name, reason: String(err?.message || err) });
    }
  }

  // Drop the per-scope install row.
  deleteInstance(service, scopeTuple);

  // For global disconnects, also clear the legacy install row so the card
  // returns to "Not connected".
  if (scopeTuple.scope === 'global') {
    try { markConnectionDisconnected(service); } catch { /* best-effort */ }
  }

  const next = getConnection(service);
  return Response.json({
    ok: true,
    connection: { ...next, status: summarizeConnection(next), installs: listInstances(service) },
    revoked,
    skipped,
    scope: scopeTuple,
  });
}
