import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

/**
 * GET /api/staff/users/[id]/links
 * Get all links for a user
 */
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const userId = params.id;

    // --- Convex data-source routing (strangler fig) ---
    // user_links is not in auth domain but uses auth domain routing for user-scoped data
    // No dedicated Convex query for user_links yet — stays with Prisma
    // --- End Convex routing ---

    const links = await prisma.user_links.findMany({
      where: { userId },
      orderBy: { sortOrder: "asc" },
    });

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

/**
 * POST /api/staff/users/[id]/links
 * Create a new link for a user
 */
export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const userId = params.id;
    const body = await request.json();
    const { linkType, title, url, description } = body;

    // Validate required fields
    if (!linkType || !title || !url) {
      return NextResponse.json(
        { error: "linkType, title, and url are required" },
        { status: 400 },
      );
    }

    // Validate URL
    try {
      new URL(url);
    } catch {
      return NextResponse.json(
        { error: "Invalid URL format" },
        { status: 400 },
      );
    }

    // Validate user exists
    const user = await prisma.users.findUnique({
      where: { id: userId },
    });

    if (!user) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    // Get the highest sortOrder for this user
    const maxSortOrder = await prisma.user_links.aggregate({
      where: { userId },
      _max: { sortOrder: true },
    });

    const link = await prisma.user_links.create({
      data: {
        userId,
        linkType,
        title,
        url,
        description: description || null,
        sortOrder: (maxSortOrder._max.sortOrder || 0) + 1,
        createdBy: staffUser.id,
      },
    });

    logger.info("Created link for user", { userId, title });

    return NextResponse.json({ link }, { status: 201 });
  } catch (error: unknown) {
    logger.error("Failed to create user link", error);
    const errorMessage =
      error instanceof Error ? error.message : "Unknown error";
    return NextResponse.json(
      { error: "Failed to create user link", details: errorMessage },
      { status: 500 },
    );
  }
}
