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

/**
 * GET /api/relay/v1/models
 *
 * Returns the aggregated model list from all of the user's online devices.
 * OpenAI-compatible format.
 */
export async function GET(req: NextRequest) {
  const user = await resolveApiKeyUser(req);
  if (!user) {
    return new Response(
      JSON.stringify({ error: { message: "Invalid API key", type: "authentication_error" } }),
      { status: 401, headers: { "Content-Type": "application/json" } },
    );
  }

  const devices = await db.device.findMany({
    where: { userId: user.id, status: "online" },
  });

  // Aggregate models from all online devices
  const modelSet = new Set<string>();
  for (const device of devices) {
    try {
      const models: string[] = JSON.parse(device.models);
      for (const m of models) modelSet.add(m);
    } catch {
      continue;
    }
  }

  const models = Array.from(modelSet).map((id) => ({
    id,
    object: "model" as const,
    created: Math.floor(Date.now() / 1000),
    owned_by: "llmhosts-local",
  }));

  return new Response(
    JSON.stringify({ object: "list", data: models }),
    { status: 200, headers: { "Content-Type": "application/json" } },
  );
}
