import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { resolveApiKeyUser } from "@/lib/api-auth";

/**
 * POST /api/devices — Register a new device.
 * Called by CLI after successful device-code auth.
 *
 * GET /api/devices — List user's devices.
 * Called by dashboard or CLI.
 *
 * Auth: Bearer token (lh_sk_* API key).
 */
export async function POST(req: NextRequest) {
  const user = await resolveApiKeyUser(req);
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await req.json();
    const { name, tunnel_url, models, hardware } = body;

    if (!name || typeof name !== "string") {
      return NextResponse.json({ error: "name is required" }, { status: 400 });
    }
    // tunnel_url is optional — device can register without a tunnel (local-only mode)
    const safeTunnelUrl = typeof tunnel_url === "string" ? tunnel_url : "";

    // Check device limit by plan
    const existingCount = await db.device.count({ where: { userId: user.id } });
    const limits: Record<string, number> = {
      free: 1,
      pro: 5,
      team: 20,
      enterprise: 100,
    };
    const limit = limits[user.plan] ?? 1;

    if (existingCount >= limit) {
      return NextResponse.json(
        { error: `Device limit reached (${limit} on ${user.plan} plan)` },
        { status: 403 },
      );
    }

    // Upsert: if device with same name exists for this user, update it
    const device = await db.device.upsert({
      where: {
        userId_name: { userId: user.id, name: name.trim() },
      },
      update: {
        tunnelUrl: safeTunnelUrl,
        models: JSON.stringify(Array.isArray(models) ? models : []),
        hardware: typeof hardware === "string" ? hardware : JSON.stringify(hardware || ""),
        status: "online",
        lastSeen: new Date(),
      },
      create: {
        userId: user.id,
        name: name.trim(),
        tunnelUrl: safeTunnelUrl,
        models: JSON.stringify(Array.isArray(models) ? models : []),
        hardware: typeof hardware === "string" ? hardware : JSON.stringify(hardware || ""),
        status: "online",
        lastSeen: new Date(),
      },
    });

    return NextResponse.json({
      id: device.id,
      name: device.name,
      tunnel_url: device.tunnelUrl,
      status: device.status,
      created_at: device.createdAt,
    }, { status: 201 });
  } catch {
    return NextResponse.json(
      { error: "Failed to register device" },
      { status: 500 },
    );
  }
}

export async function GET(req: NextRequest) {
  const user = await resolveApiKeyUser(req);
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const devices = await db.device.findMany({
      where: { userId: user.id },
      orderBy: { lastSeen: "desc" },
    });

    return NextResponse.json({
      devices: devices.map((d) => ({
        id: d.id,
        name: d.name,
        tunnel_url: d.tunnelUrl,
        models: JSON.parse(d.models),
        hardware: d.hardware,
        status: d.status,
        last_seen: d.lastSeen,
        latency_ms: d.latencyMs,
      })),
    });
  } catch {
    return NextResponse.json(
      { error: "Failed to list devices" },
      { status: 500 },
    );
  }
}
