import { prisma } from '@/lib/prisma';

/**
 * Set a saved AIConfigProfile as the actor's active config + mirror its
 * fields into the legacy UserPreferences columns so any code path that
 * reads aiProvider/aiModel/aiBaseUrl/aiApiKey from prefs (api/ai/test,
 * api/ai/generate's existing reads) keeps working without conditional
 * logic.
 *
 * Lives outside the route file because Next.js App Router only allows
 * HTTP method exports (GET / POST / etc.) from route.ts modules.
 */
export async function activate(
  userId: string,
  profileId: string,
  fields: {
    provider: string;
    model: string;
    baseUrl?: string | null;
    apiKey?: string | null;
  },
) {
  await prisma.userPreferences.upsert({
    where: { userId },
    update: {
      activeAIConfigId: profileId,
      aiProvider: fields.provider,
      aiModel: fields.model,
      aiBaseUrl: fields.baseUrl || null,
      aiApiKey: fields.apiKey || null,
    },
    create: {
      userId,
      theme: 'system',
      defaultWeightUnit: 'lbs',
      defaultRestSeconds: 90,
      activeAIConfigId: profileId,
      aiProvider: fields.provider,
      aiModel: fields.model,
      aiBaseUrl: fields.baseUrl || null,
      aiApiKey: fields.apiKey || null,
    },
  });
}
