import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { getCurrentUser } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

/**
 * GET  /api/ai/config  — read this user's AI provider config.
 *                         API key is NOT returned in plaintext (only
 *                         a "configured: true|false" flag) so it
 *                         doesn't leak via Settings page reload.
 * POST /api/ai/config  — update. Pass null/empty to clear a field.
 */

export async function GET() {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const prefs = await prisma.userPreferences.findUnique({
    where: { userId: user.id },
    select: { aiProvider: true, aiModel: true, aiBaseUrl: true, aiApiKey: true },
  });
  return NextResponse.json({
    aiProvider: prefs?.aiProvider ?? null,
    aiModel: prefs?.aiModel ?? null,
    aiBaseUrl: prefs?.aiBaseUrl ?? null,
    aiKeyConfigured: !!prefs?.aiApiKey,
  });
}

const bodySchema = z.object({
  aiProvider: z
    .enum(['claude', 'openai', 'openai-compatible', 'gemini', 'ollama'])
    .nullable()
    .optional(),
  aiModel: z.string().nullable().optional(),
  aiBaseUrl: z.string().url().nullable().optional().or(z.literal('')),
  aiApiKey: z.string().nullable().optional(),
});

export async function POST(request: NextRequest) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const body = await request.json().catch(() => ({}));
  const parsed = bodySchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { error: 'Invalid body', details: parsed.error.errors },
      { status: 400 },
    );
  }

  // Empty string -> null (UI sometimes sends "")
  const norm = (v: string | null | undefined) =>
    v === '' || v == null ? null : v;

  const data: Record<string, string | null> = {};
  if (parsed.data.aiProvider !== undefined)
    data.aiProvider = parsed.data.aiProvider ?? null;
  if (parsed.data.aiModel !== undefined) data.aiModel = norm(parsed.data.aiModel);
  if (parsed.data.aiBaseUrl !== undefined)
    data.aiBaseUrl = norm(parsed.data.aiBaseUrl);
  if (parsed.data.aiApiKey !== undefined)
    data.aiApiKey = norm(parsed.data.aiApiKey);

  // Make sure the prefs row exists.
  await prisma.userPreferences.upsert({
    where: { userId: user.id },
    update: data,
    create: {
      userId: user.id,
      theme: 'system',
      defaultWeightUnit: 'lbs',
      defaultRestSeconds: 90,
      ...data,
    },
  });

  return NextResponse.json({ success: true });
}
