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

/**
 * GET    /api/ai/configs/[id]   Single config (apiKey redacted).
 * PATCH  /api/ai/configs/[id]   Update fields. Empty/null clears.
 *                                Re-mirrors to UserPreferences if active.
 * DELETE /api/ai/configs/[id]   Remove. If it was active, falls back to
 *                                the most-recently-created remaining
 *                                profile (or clears if none left).
 */

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

  const p = await prisma.aIConfigProfile.findFirst({
    where: { id: params.id, userId: user.id },
    select: {
      id: true,
      name: true,
      provider: true,
      model: true,
      baseUrl: true,
      apiKey: true,
      createdAt: true,
    },
  });
  if (!p) return NextResponse.json({ error: 'Not found' }, { status: 404 });
  return NextResponse.json({
    id: p.id,
    name: p.name,
    provider: p.provider,
    model: p.model,
    baseUrl: p.baseUrl,
    keyConfigured: !!p.apiKey,
    createdAt: p.createdAt.toISOString(),
  });
}

const patchSchema = z.object({
  name: z.string().min(1).max(80).optional(),
  model: z.string().min(1).max(200).optional(),
  baseUrl: z.string().url().nullable().optional().or(z.literal('')),
  apiKey: z.string().nullable().optional(),
});

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

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

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

  const data: Record<string, string | null> = {};
  if (parsed.data.name !== undefined) data.name = parsed.data.name;
  if (parsed.data.model !== undefined) data.model = parsed.data.model;
  if (parsed.data.baseUrl !== undefined)
    data.baseUrl = parsed.data.baseUrl || null;
  if (parsed.data.apiKey !== undefined)
    data.apiKey = parsed.data.apiKey || null;

  const updated = await prisma.aIConfigProfile.update({
    where: { id: params.id },
    data,
  });

  // If this was the active config, mirror the new fields back into
  // UserPreferences so existing read paths (api/ai/test, api/ai/generate
  // current implementation) see the latest values.
  const prefs = await prisma.userPreferences.findUnique({
    where: { userId: user.id },
    select: { activeAIConfigId: true },
  });
  if (prefs?.activeAIConfigId === params.id) {
    await activate(user.id, params.id, {
      provider: updated.provider,
      model: updated.model,
      baseUrl: updated.baseUrl,
      apiKey: updated.apiKey,
    });
  }

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

export async function DELETE(
  _req: NextRequest,
  { params }: { params: { id: string } },
) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

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

  await prisma.aIConfigProfile.delete({ where: { id: params.id } });

  // If we just deleted the active config, demote-or-remove gracefully.
  const prefs = await prisma.userPreferences.findUnique({
    where: { userId: user.id },
    select: { activeAIConfigId: true },
  });
  if (prefs?.activeAIConfigId === params.id) {
    const fallback = await prisma.aIConfigProfile.findFirst({
      where: { userId: user.id },
      orderBy: { createdAt: 'desc' },
    });
    if (fallback) {
      await activate(user.id, fallback.id, {
        provider: fallback.provider,
        model: fallback.model,
        baseUrl: fallback.baseUrl,
        apiKey: fallback.apiKey,
      });
    } else {
      await prisma.userPreferences.update({
        where: { userId: user.id },
        data: {
          activeAIConfigId: null,
          aiProvider: null,
          aiModel: null,
          aiBaseUrl: null,
          aiApiKey: null,
        },
      });
    }
  }

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