import { NextResponse } from "next/server";
import { badRequest, logApiError, readJsonBody } from "@/lib/api/security";
import { getDefaultModel } from "@/lib/ai/catalog";
import { getAISettingsPublic, saveAISettings } from "@/lib/ai/settings";
import type { AIProvider } from "@/lib/ai/types";
import { createRouteClient } from "@/lib/supabase/route";

function isAIProvider(value: unknown): value is AIProvider {
  return value === "mindavio_core" || value === "openai" || value === "anthropic";
}

export async function GET() {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const settings = await getAISettingsPublic(user.id);
    return NextResponse.json(settings);
  } catch (error) {
    logApiError("AI settings GET error", error);
    return NextResponse.json({ error: "Failed to load AI settings" }, { status: 500 });
  }
}

export async function POST(req: Request) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await readJsonBody<{
      provider?: unknown;
      model?: unknown;
      openaiApiKey?: unknown;
      anthropicApiKey?: unknown;
      clearOpenAIKey?: unknown;
      clearAnthropicKey?: unknown;
      customInstructions?: unknown;
    }>(req);
    if (!body) return badRequest();

    const provider = isAIProvider(body.provider) ? body.provider : "mindavio_core";
    const model =
      typeof body.model === "string" && body.model.trim()
        ? body.model.trim()
        : getDefaultModel(provider);

    const settings = await saveAISettings({
      userId: user.id,
      provider,
      model,
      openaiApiKey: typeof body.openaiApiKey === "string" ? body.openaiApiKey : undefined,
      anthropicApiKey: typeof body.anthropicApiKey === "string" ? body.anthropicApiKey : undefined,
      clearOpenAIKey: Boolean(body.clearOpenAIKey),
      clearAnthropicKey: Boolean(body.clearAnthropicKey),
      customInstructions:
        typeof body.customInstructions === "string" ? body.customInstructions : undefined,
    });

    return NextResponse.json(settings);
  } catch (error) {
    logApiError("AI settings POST error", error);
    return NextResponse.json({ error: "Failed to save AI settings" }, { status: 500 });
  }
}
