/**
 * /api/settings — User preferences dan legacy API key settings
 *
 * DEPRECATION NOTICE:
 * Menyimpan API key di user_settings (plaintext) sudah deprecated.
 * Gunakan /api/env-vars yang menyimpan key dengan enkripsi AES-256-GCM.
 *
 * Route ini masih:
 * - GET: mengembalikan preferences + status apakah key sudah diset (masked)
 * - POST: hanya menyimpan preferences (bahasa, mode, dll)
 *   — API key yang dikirim via POST diabaikan; arahkan user ke /api/env-vars
 * - PUT: test koneksi key yang sudah ada di DB (baca dari env_vars via resolver)
 */

import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { resolveUserEnvVarsCached, hasAnyAiKey } from "@/lib/env-vars-resolver";
import { isCsrfSafe, csrfForbiddenPayload } from "@/lib/csrf";

// Mask API key — tampilkan hanya 4 karakter terakhir
function maskKey(key: string | null | undefined): string {
  if (!key || key.length < 8) return "";
  return "•".repeat(key.length - 4) + key.slice(-4);
}

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

  type UserSettingsRow = {
    preferred_ai_provider?: string | null;
    preferred_model?: string | null;
    default_language?: string | null;
    default_mode?: string | null;
    default_variations?: number | null;
    email_notifications?: boolean | null;
    openai_api_key?: string | null;
    anthropic_api_key?: string | null;
    google_ai_api_key?: string | null;
    supabase_url?: string | null;
    supabase_anon_key?: string | null;
  };

  const { data: rawData, error } = await supabase
    .from("user_settings")
    .select(
      "preferred_ai_provider, preferred_model, default_language, default_mode, " +
      "default_variations, email_notifications, " +
      // Baca legacy columns hanya untuk status/mask — jangan expose nilainya
      "openai_api_key, anthropic_api_key, google_ai_api_key, supabase_url, supabase_anon_key"
    )
    .eq("user_id", user.id)
    .single();

  if (error && error.code !== "PGRST116") {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }

  const data: UserSettingsRow | null = rawData
    ? (rawData as unknown as UserSettingsRow)
    : null;

  // Jangan kirim raw key ke frontend — kirim masked version + status
  const safeData = {
    preferred_ai_provider:  data?.preferred_ai_provider  ?? "auto",
    preferred_model:        data?.preferred_model        ?? null,
    default_language:       data?.default_language       ?? "id",
    default_mode:           data?.default_mode           ?? "simple",
    default_variations:     data?.default_variations     ?? 1,
    email_notifications:    data?.email_notifications    ?? true,
    // Masked legacy keys — hanya untuk backward-compat UI
    openai_api_key_masked:      maskKey(data?.openai_api_key),
    anthropic_api_key_masked:   maskKey(data?.anthropic_api_key),
    google_ai_api_key_masked:   maskKey(data?.google_ai_api_key),
    supabase_url_masked:        data?.supabase_url ?? "",
    supabase_anon_key_masked:   maskKey(data?.supabase_anon_key),
    // Status — apakah key sudah diset (legacy atau env_vars)
    has_openai_key:      !!data?.openai_api_key,
    has_anthropic_key:   !!data?.anthropic_api_key,
    has_google_key:      !!data?.google_ai_api_key,
    has_supabase_config: !!(data?.supabase_url && data?.supabase_anon_key),
    // Flag untuk UI: sarankan migrasi ke env_vars
    legacy_keys_warning: !!(
      data?.openai_api_key ||
      data?.anthropic_api_key ||
      data?.google_ai_api_key
    ),
  };

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

export async function POST(request: NextRequest) {
  // BUG-13 FIX: CSRF check
  if (!isCsrfSafe(request)) {
    return NextResponse.json(csrfForbiddenPayload(), { status: 403 });
  }

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

  const body = await request.json();

  // Hanya terima preference fields — API key TIDAK disimpan di sini lagi.
  // Gunakan POST /api/env-vars untuk menyimpan API key secara aman (AES-256-GCM).
  const allowedFields: Record<string, unknown> = {};

  if (body.preferred_ai_provider !== undefined) {
    allowedFields.preferred_ai_provider = body.preferred_ai_provider;
  }
  if (body.preferred_model !== undefined) {
    allowedFields.preferred_model = body.preferred_model || null;
  }
  if (body.default_language !== undefined) {
    allowedFields.default_language = body.default_language;
  }
  if (body.default_mode !== undefined) {
    allowedFields.default_mode = body.default_mode;
  }
  if (body.default_variations !== undefined) {
    allowedFields.default_variations = body.default_variations;
  }
  if (body.email_notifications !== undefined) {
    allowedFields.email_notifications = body.email_notifications;
  }

  // Log jika ada percobaan simpan API key via route ini
  const legacyKeyFields = ["openai_api_key", "anthropic_api_key", "google_ai_api_key", "supabase_anon_key"];
  const hasLegacyKey = legacyKeyFields.some((k) => body[k] !== undefined && !String(body[k] ?? "").includes("•"));
  if (hasLegacyKey) {
    console.warn(
      `[settings] User ${user.id} mencoba simpan API key via /api/settings (deprecated). ` +
      "Arahkan ke /api/env-vars untuk penyimpanan terenkripsi."
    );
    // Kembalikan pesan deprecation — jangan simpan key plaintext
    return NextResponse.json(
      {
        success: false,
        deprecated: true,
        error:
          "Menyimpan API key di sini sudah deprecated. " +
          "Gunakan endpoint /api/env-vars untuk menyimpan API key secara aman (enkripsi AES-256-GCM).",
        redirect: "/settings?tab=api-keys",
      },
      { status: 410 }
    );
  }

  const { error } = await supabase
    .from("user_settings")
    .upsert(
      { user_id: user.id, ...allowedFields },
      { onConflict: "user_id" }
    );

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

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

// Test koneksi API key — baca dari env_vars (encrypted) via resolver
export async function PUT(request: NextRequest) {
  // BUG-13 FIX: CSRF check
  if (!isCsrfSafe(request)) {
    return NextResponse.json(csrfForbiddenPayload(), { status: 403 });
  }

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

  const { provider } = await request.json();

  // Baca key dari env_vars (terenkripsi) — bukan dari user_settings (plaintext)
  const resolvedVars = await resolveUserEnvVarsCached(supabase, user.id);

  if (!hasAnyAiKey(resolvedVars)) {
    return NextResponse.json({
      success: false,
      error: "Belum ada API key yang dikonfigurasi. Tambahkan di Settings → API Keys.",
    });
  }

  try {
    if (provider === "openai" && resolvedVars.openaiApiKey) {
      const res = await fetch("https://api.openai.com/v1/models", {
        headers: { Authorization: `Bearer ${resolvedVars.openaiApiKey}` },
      });
      if (!res.ok) throw new Error("Invalid OpenAI API key");
      return NextResponse.json({ success: true, provider: "openai" });
    }

    if (provider === "anthropic" && resolvedVars.anthropicApiKey) {
      const res = await fetch("https://api.anthropic.com/v1/messages", {
        method: "POST",
        headers: {
          "x-api-key":         resolvedVars.anthropicApiKey,
          "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" }],
        }),
      });
      // 400 = request valid tapi bad input → key valid
      if (res.status !== 200 && res.status !== 400) throw new Error("Invalid Anthropic API key");
      return NextResponse.json({ success: true, provider: "anthropic" });
    }

    if (provider === "google" && resolvedVars.googleAiApiKey) {
      const res = await fetch(
        `https://generativelanguage.googleapis.com/v1beta/models?key=${resolvedVars.googleAiApiKey}`
      );
      if (!res.ok) throw new Error("Invalid Google AI API key");
      return NextResponse.json({ success: true, provider: "google" });
    }

    if (provider === "agentrouter" && resolvedVars.agentRouterApiKey) {
      const res = await fetch("https://agentrouter.org/v1/models", {
        headers: { Authorization: `Bearer ${resolvedVars.agentRouterApiKey}` },
      });
      if (!res.ok) throw new Error("Invalid AgentRouter API key");
      return NextResponse.json({ success: true, provider: "agentrouter" });
    }

    return NextResponse.json({
      success: false,
      error: `API key untuk provider "${provider}" belum dikonfigurasi.`,
    });
  } catch (e) {
    return NextResponse.json({ success: false, error: (e as Error).message });
  }
}
