/**
 * /api/env-vars/test
 * POST { key } — test apakah API key yang tersimpan valid
 * Dekripsi & koneksi dilakukan SEPENUHNYA di server.
 */

import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { decrypt } from "@/lib/crypto";
import type { EnvVar } from "@/types/env-vars";

export async function POST(request: NextRequest) {
  const supabase = createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { key } = await request.json() as { key: string };
  if (!key) return NextResponse.json({ error: "Key diperlukan" }, { status: 400 });

  // Ambil encrypted value dari DB
  const { data, error } = await supabase
    .from("env_vars")
    .select("id, encrypted_value")
    .eq("user_id", user.id)
    .eq("key", key)
    .eq("is_active", true)
    .single();

  if (error || !data) {
    return NextResponse.json({ success: false, error: "Key tidak ditemukan atau tidak aktif" });
  }

  // Dekripsi
  let plainValue: string;
  try {
    plainValue = decrypt((data as EnvVar).encrypted_value);
  } catch {
    return NextResponse.json({ success: false, error: "Gagal dekripsi — ENCRYPTION_SECRET mungkin berubah" });
  }

  // Test koneksi berdasarkan key
  try {
    let result: { success: boolean; info?: string } = { success: false };

    if (key === "OPENAI_API_KEY") {
      const res = await fetch("https://api.openai.com/v1/models", {
        headers: { Authorization: `Bearer ${plainValue}` },
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json() as { data: Array<{ id: string }> };
      result = { success: true, info: `${json.data.length} model tersedia` };
    }

    else if (key === "ANTHROPIC_API_KEY") {
      const res = await fetch("https://api.anthropic.com/v1/messages", {
        method: "POST",
        headers: {
          "x-api-key": plainValue,
          "anthropic-version": "2023-06-01",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          model: "claude-3-haiku-20240307",
          max_tokens: 1,
          messages: [{ role: "user", content: "hi" }],
        }),
      });
      // 200 atau 400 (bad request) → key valid
      if (res.status !== 200 && res.status !== 400) throw new Error(`HTTP ${res.status}`);
      result = { success: true, info: "Anthropic API key valid" };
    }

    else if (key === "GOOGLE_AI_API_KEY") {
      const res = await fetch(
        `https://generativelanguage.googleapis.com/v1beta/models?key=${plainValue}`
      );
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json() as { models: unknown[] };
      result = { success: true, info: `${json.models?.length ?? 0} model tersedia` };
    }

    else if (key === "AGENTROUTER_API_KEY") {
      // Test dengan hit /v1/models endpoint AgentRouter (OpenAI-compatible)
      const res = await fetch("https://agentrouter.org/v1/models", {
        headers: {
          Authorization:  `Bearer ${plainValue}`,
          "HTTP-Referer": "https://promptmotion.ai",
          "X-Title":      "PromptMotion AI",
        },
      });
      if (!res.ok) throw new Error(`HTTP ${res.status} — key mungkin invalid atau expired`);
      const json = await res.json() as { data?: unknown[] };
      const count = Array.isArray(json.data) ? json.data.length : "?";
      result = { success: true, info: `AgentRouter key valid — ${count} model tersedia` };
    }

    else {
      // Key bukan provider — cukup pastikan terenkripsi & bisa didekripsi
      result = { success: true, info: "Value berhasil didekripsi" };
    }

    // Update last_used_at
    await supabase
      .from("env_vars")
      .update({ last_used_at: new Date().toISOString() })
      .eq("id", (data as EnvVar).id);

    return NextResponse.json(result);
  } catch (e) {
    return NextResponse.json({ success: false, error: (e as Error).message });
  }
}
