import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { convexQuery } from "@/lib/convex-client";
import { getAuthenticatedConvexUser } from "@/lib/convex-auth-state";

export const dynamic = "force-dynamic";

interface ConvexUserLink {
  _id: string;
  linkType: string;
  title: string;
  url: string;
  description?: string;
  icon?: string;
  sortOrder: number;
}

/**
 * GET /api/user/links
 *
 * Get all active links for the authenticated user.
 * Users can only view their own links (read-only).
 * Links are managed by admin/staff via the staff dashboard.
 */
export async function GET(request: NextRequest) {
  try {
    // Authenticate user via Convex auth state
    const user = await getAuthenticatedConvexUser(request, auth);

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Fetch active links from Convex (sorted by sortOrder in the query)
    const links = await convexQuery<ConvexUserLink[]>(
      "auth/queries:getUserLinks",
      {
        userId: user._id,
      },
    );

    const formattedLinks = (links ?? []).map((link) => ({
      id: link._id,
      linkType: link.linkType,
      title: link.title,
      url: link.url,
      description: link.description,
      icon: link.icon,
      sortOrder: link.sortOrder,
    }));

    return NextResponse.json({ links: formattedLinks });
  } catch (error) {
    console.error("Failed to fetch user links:", error);
    return NextResponse.json(
      { error: "Failed to fetch links" },
      { status: 500 },
    );
  }
}
