import { NextRequest, NextResponse } from 'next/server';
import { getCurrentUser } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { activate } from '@/lib/ai/activateConfig';

/**
 * POST /api/ai/configs/[id]/activate
 *
 * Set the named profile as the actor's active AI config. Mirrors the
 * profile's fields into UserPreferences (legacy single-config columns)
 * so api/ai/generate + api/ai/test continue to work as-is.
 */
export async function POST(
  _req: NextRequest,
  { params }: { params: { id: string } },
) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const profile = await prisma.aIConfigProfile.findFirst({
    where: { id: params.id, userId: user.id },
  });
  if (!profile) return NextResponse.json({ error: 'Not found' }, { status: 404 });

  await activate(user.id, profile.id, {
    provider: profile.provider,
    model: profile.model,
    baseUrl: profile.baseUrl,
    apiKey: profile.apiKey,
  });

  return NextResponse.json({ success: true, activeId: profile.id });
}
