// In-memory credential store (MVP)
// In production, this would be backed by a database

interface StoredCredential {
  service: string;
  connectedAt: string;
}

const credentialStore = new Map<string, StoredCredential>();

export async function GET() {
  const credentials: Record<string, StoredCredential> = {};
  for (const [type, cred] of credentialStore.entries()) {
    credentials[type] = cred;
  }
  return Response.json({ credentials });
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { type, service } = body as { type: string; service: string };

    if (!type || !service) {
      return Response.json(
        { error: "Missing 'type' and 'service' fields" },
        { status: 400 }
      );
    }

    credentialStore.set(type, {
      service,
      connectedAt: new Date().toISOString(),
    });

    return Response.json({ ok: true, type, service });
  } catch {
    return Response.json({ error: "Invalid JSON" }, { status: 400 });
  }
}

export async function DELETE(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const type = searchParams.get("type");

    if (type) {
      credentialStore.delete(type);
    } else {
      credentialStore.clear();
    }

    return Response.json({ ok: true });
  } catch {
    return Response.json({ error: "Failed to delete" }, { status: 500 });
  }
}
