import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth/jwt";
import { deleteApiKey, getApiKeyById, updateApiKey, deleteApiKeyForUser } from "@/lib/localDb";

async function getUserIdFromJwt() {
  const cookieStore = await cookies();
  const token = cookieStore.get("auth_token")?.value;
  if (!token) return null;
  const payload = await verifyToken(token);
  return payload?.userId || null;
}

async function requireAdmin() {
  const cookieStore = await cookies();
  const token = cookieStore.get("auth_token")?.value;
  if (!token) return null;
  const payload = await verifyToken(token);
  if (!payload || payload.role !== "admin") return null;
  return payload;
}

// GET /api/keys/[id] - Get single key
export async function GET(request, { params }) {
  try {
    const { id } = await params;
    const key = await getApiKeyById(id);
    if (!key) {
      return NextResponse.json({ error: "Key not found" }, { status: 404 });
    }
    return NextResponse.json({ key });
  } catch (error) {
    console.log("Error fetching key:", error);
    return NextResponse.json({ error: "Failed to fetch key" }, { status: 500 });
  }
}

// PUT /api/keys/[id] - Update key (comment, isActive, name)
export async function PUT(request, { params }) {
  try {
    const { id } = await params;
    const body = await request.json();
    const { isActive, comment, name } = body;

    const existing = await getApiKeyById(id);
    if (!existing) {
      return NextResponse.json({ error: "Key not found" }, { status: 404 });
    }

    const updateData = {};
    if (isActive !== undefined) updateData.isActive = isActive;
    if (comment !== undefined) updateData.comment = comment;
    if (name !== undefined) updateData.name = name;

    const updated = await updateApiKey(id, updateData);

    return NextResponse.json({ key: updated });
  } catch (error) {
    console.log("Error updating key:", error);
    return NextResponse.json({ error: "Failed to update key" }, { status: 500 });
  }
}

// PATCH /api/keys/[id] - Update per-key RTK/Caveman settings
export async function PATCH(request, { params }) {
  try {
    const { id } = await params;
    const body = await request.json();
    const { rtkEnabled, cavemanEnabled, cavemanLevel } = body;

    const existing = await getApiKeyById(id);
    if (!existing) {
      return NextResponse.json({ error: "Key not found" }, { status: 404 });
    }

    const updateData = {};
    if (rtkEnabled !== undefined) updateData.rtkEnabled = rtkEnabled;
    if (cavemanEnabled !== undefined) updateData.cavemanEnabled = cavemanEnabled;
    if (cavemanLevel !== undefined) updateData.cavemanLevel = cavemanLevel;

    const updated = await updateApiKey(id, updateData);

    return NextResponse.json({ key: updated });
  } catch (error) {
    console.log("Error updating key settings:", error);
    return NextResponse.json({ error: "Failed to update key settings" }, { status: 500 });
  }
}

// DELETE /api/keys/[id] - Delete API key (admin can delete any, user can delete own)
export async function DELETE(request, { params }) {
  try {
    const { id } = await params;

    const admin = await requireAdmin();
    let deleted;

    if (admin) {
      deleted = await deleteApiKey(id);
    } else {
      const userId = await getUserIdFromJwt();
      if (!userId) {
        return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
      }
      deleted = await deleteApiKeyForUser(id, userId);
    }

    if (!deleted) {
      return NextResponse.json({ error: "Key not found" }, { status: 404 });
    }

    return NextResponse.json({ message: "Key deleted successfully" });
  } catch (error) {
    console.log("Error deleting key:", error);
    return NextResponse.json({ error: "Failed to delete key" }, { status: 500 });
  }
}
