/**
 * /api/admin/api-keys
 *
 * GET    — list global API keys (masked)
 * POST   — upsert a global API key
 * DELETE — delete by key_name (?key_name=...)
 * PUT    — test a stored key (?test=key_name)
 *
 * Admin-only.
 */

import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { encrypt, decrypt, maskValue } from "@/lib/crypto";
import { isCsrfSafe, csrfForbiddenPayload } from "@/lib/csrf";

async function requireAdmin(supabase: ReturnType<typeof createClient>) {
  const { data: { user }, error } = await supabase.auth.getUser();
  if (error || !user) return null;
  const { data: profile } = await supabase
    .from("profiles")
    .select("role")
    .eq("id", user.id)
    .single();
  if (profile?.role !== "admin") return null;
  return user;
}

// ── GET ──────────────────────────────────────────────────────────────────────
export async function GET(request: NextRequest) {
  const supabase = createClient();
  const admin = await requireAdmin(supabase);
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const { searchParams } = new URL(request.url);
  const testKey = searchParams.get("test");

  // Test mode: verify a stored key live
  if (testKey) {
    const { data, error } = await supabase
      .from("global_api_keys")
      .select("key_name, encrypted_value, provider")
      .eq("key_name", testKey)
      .eq("is_active", true)
      .single();

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

    let plain: string;
    try {
      plain = decrypt(data.encrypted_value);
    } catch {
      return NextResponse.json({ success: false, error: "Gagal dekripsi key" });
    }

    try {
      if (data.provider === "openai") {
        const res = await fetch("https://api.openai.com/v1/models", {
          headers: { Authorization: `Bearer ${plain}` },
        });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const json = await res.json() as { data: unknown[] };
        return NextResponse.json({ success: true, info: `${json.data.length} models tersedia` });
      }
      if (data.provider === "anthropic") {
        const res = await fetch("https://api.anthropic.com/v1/messages", {
          method: "POST",
          headers: {
            "x-api-key": plain,
            "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" }] }),
        });
        if (res.status !== 200 && res.status !== 400) throw new Error(`HTTP ${res.status}`);
        return NextResponse.json({ success: true, info: "Anthropic key valid" });
      }
      if (data.provider === "google") {
        const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${plain}`);
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const json = await res.json() as { models: unknown[] };
        return NextResponse.json({ success: true, info: `${json.models?.length ?? 0} models tersedia` });
      }
      return NextResponse.json({ success: true, info: "Key valid (non-AI provider)" });
    } catch (e) {
      return NextResponse.json({ success: false, error: (e as Error).message });
    }
  }

  // List all keys (masked)
  const { data, error } = await supabase
    .from("global_api_keys")
    .select("id, key_name, provider, is_active, description, last_used_at, updated_at, encrypted_value")
    .order("provider")
    .order("key_name");

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

  const safe = (data ?? []).map((row) => {
    let masked = "••••••";
    try { masked = maskValue(decrypt(row.encrypted_value)); } catch { /* */ }
    return {
      id: row.id,
      key_name: row.key_name,
      provider: row.provider,
      is_active: row.is_active,
      description: row.description,
      masked_value: masked,
      last_used_at: row.last_used_at,
      updated_at: row.updated_at,
    };
  });

  return NextResponse.json({ data: safe });
}

// ── POST — upsert key ─────────────────────────────────────────────────────────
export async function POST(request: NextRequest) {
  // Fix Issue B: CSRF check
  if (!isCsrfSafe(request)) return NextResponse.json(csrfForbiddenPayload(), { status: 403 });
  const supabase = createClient();
  const admin = await requireAdmin(supabase);
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const body = await request.json() as {
    key_name: string;
    value: string;
    provider: string;
    description?: string;
  };

  if (!body.key_name || !body.value || !body.provider) {
    return NextResponse.json({ error: "key_name, value, provider wajib diisi" }, { status: 400 });
  }
  if (body.value.includes("•")) {
    return NextResponse.json({ error: "Value tidak boleh berisi karakter mask" }, { status: 400 });
  }

  const encryptedValue = encrypt(body.value.trim());

  const { error } = await supabase.rpc("upsert_global_api_key", {
    p_key_name: body.key_name,
    p_encrypted_val: encryptedValue,
    p_provider: body.provider,
    p_description: body.description ?? null,
  });

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });
  return NextResponse.json({ success: true });
}

// ── DELETE ────────────────────────────────────────────────────────────────────
export async function DELETE(request: NextRequest) {
  // Fix Issue B: CSRF check
  if (!isCsrfSafe(request)) return NextResponse.json(csrfForbiddenPayload(), { status: 403 });
  const supabase = createClient();
  const admin = await requireAdmin(supabase);
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const { searchParams } = new URL(request.url);
  const keyName = searchParams.get("key_name");
  if (!keyName) return NextResponse.json({ error: "key_name diperlukan" }, { status: 400 });

  const { error } = await supabase
    .from("global_api_keys")
    .delete()
    .eq("key_name", keyName);

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });
  return NextResponse.json({ success: true });
}

// ── PATCH — toggle is_active ──────────────────────────────────────────────────
export async function PATCH(request: NextRequest) {
  // Fix Issue B: CSRF check
  if (!isCsrfSafe(request)) return NextResponse.json(csrfForbiddenPayload(), { status: 403 });
  const supabase = createClient();
  const admin = await requireAdmin(supabase);
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

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

  const { error } = await supabase
    .from("global_api_keys")
    .update({ is_active })
    .eq("key_name", key_name);

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });
  return NextResponse.json({ success: true });
}
