import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

/**
 * GET /api/dashboard/devices
 *
 * Returns the current user's registered devices (session auth).
 * Used by the dashboard Devices page.
 */
export async function GET() {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const devices = await db.device.findMany({
      where: { userId: session.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 || "[]") as string[],
        hardware: d.hardware,
        status: d.status,
        last_seen: d.lastSeen,
        latency_ms: d.latencyMs,
        created_at: d.createdAt,
        // Enhanced heartbeat fields
        vram_usage_mb: d.vramUsageMb,
        active_model: d.activeModel,
        requests_served: d.requestsServed,
        uptime_seconds: d.uptimeSeconds,
        savings_usd: d.savingsUsd,
        marketplace_enabled: d.marketplaceEnabled,
        price_cents_per_hour: d.marketplacePriceCents,
      })),
    });
  } catch {
    return NextResponse.json(
      { error: "Failed to load devices" },
      { status: 500 }
    );
  }
}
