import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { verifyToken } from "@/lib/auth/jwt";
import { getApiKeys, createApiKey, findByUserId } from "@/lib/localDb";
import { getConsistentMachineId } from "@/shared/utils/machineId";

export const dynamic = "force-dynamic";

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 — List keys (admin sees all, user sees own)
export async function GET(request) {
  try {
    let adminRequestedUserId = null;
    let showAll = false;
    if (request?.url) {
      const { searchParams } = new URL(request.url);
      adminRequestedUserId = searchParams.get("userId");
      showAll = searchParams.get("all") === "true";
    }

    if (showAll) {
      const admin = await requireAdmin();
      if (!admin) {
        return NextResponse.json({ error: "Forbidden" }, { status: 403 });
      }
      const keys = await getApiKeys();
      return NextResponse.json({ keys });
    }

    if (adminRequestedUserId) {
      const admin = await requireAdmin();
      if (!admin) {
        return NextResponse.json({ error: "Forbidden" }, { status: 403 });
      }
      const keys = await findByUserId(adminRequestedUserId);
      return NextResponse.json({ keys });
    }

    const userId = await getUserIdFromJwt();
    if (!userId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    const keys = await findByUserId(userId);
    return NextResponse.json({ keys });
  } catch (error) {
    console.log("Error fetching keys:", error);
    return NextResponse.json({ error: "Failed to fetch keys" }, { status: 500 });
  }
}

// POST /api/keys — Create API key (admin can specify userId + comment)
export async function POST(request) {
  try {
    const body = await request.json();
    const { name, userId: bodyUserId, comment } = body;

    if (!name) {
      return NextResponse.json({ error: "Name is required" }, { status: 400 });
    }

    let targetUserId;
    const admin = await requireAdmin();

    if (bodyUserId) {
      if (!admin) {
        return NextResponse.json({ error: "Forbidden" }, { status: 403 });
      }
      targetUserId = bodyUserId;
    } else if (admin) {
      // Admin creating for self — use their own userId
      targetUserId = admin.userId;
    } else {
      const jwtUserId = await getUserIdFromJwt();
      if (!jwtUserId) {
        return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
      }
      targetUserId = jwtUserId;
    }

    const machineId = await getConsistentMachineId();
    const apiKey = await createApiKey(name, targetUserId, machineId, comment ?? "");

    return NextResponse.json({
      key: apiKey.key,
      name: apiKey.name,
      id: apiKey.id,
      machineId: apiKey.machineId,
      userId: apiKey.userId,
      comment: apiKey.comment,
    }, { status: 201 });
  } catch (error) {
    console.log("Error creating key:", error);
    return NextResponse.json({ error: "Failed to create key" }, { status: 500 });
  }
}
