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";
// user_links Convex routing: No dedicated Convex mutations for user_links yet.
// Data stays with Prisma. Import is added for future routing readiness.

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

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

    // Verify the link exists and belongs to the user
    const existingLink = await prisma.user_links.findFirst({
      where: { id: linkId, userId },
    });

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

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

    const updateData: Record<string, unknown> = {
      updatedBy: staffUser.id,
    };

    if (linkType !== undefined) updateData.linkType = linkType;
    if (title !== undefined) updateData.title = title;
    if (url !== undefined) updateData.url = url;
    if (description !== undefined) updateData.description = description;
    if (isActive !== undefined) updateData.isActive = isActive;
    if (sortOrder !== undefined) updateData.sortOrder = sortOrder;

    const link = await prisma.user_links.update({
      where: { id: linkId },
      data: updateData,
    });

    logger.info("Updated link for user", { linkId, userId });

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

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

    const { id: userId, linkId } = params;

    // Verify the link exists and belongs to the user
    const existingLink = await prisma.user_links.findFirst({
      where: { id: linkId, userId },
    });

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

    await prisma.user_links.delete({
      where: { id: linkId },
    });

    logger.info("Deleted link for user", { linkId, userId });

    return NextResponse.json({ success: true });
  } catch (error) {
    logger.error("Failed to delete user link", error);
    return NextResponse.json(
      { error: "Failed to delete user link" },
      { status: 500 },
    );
  }
}
