import { json } from "@remix-run/node";
import prisma from "../db.server";

export const loader = async ({ request }) => {
  try {
    const url = new URL(request.url);
    const userIdRaw = url.searchParams.get("userId");
    const productIdRaw = url.searchParams.get("productId") || "";

    // validate userId
    const userId = parseInt(userIdRaw, 10);
    if (!userIdRaw || Number.isNaN(userId)) {
      return json({ error: "Invalid or missing userId" }, { status: 400 });
    }

    // parse productId string into array, convert to integers, filter invalid
    const productIdArray = productIdRaw
      .split(",")
      .map(s => s.trim())
      .filter(s => s !== "");

    // convert to numbers (Prisma expects Int)
    const productIdInts = productIdArray
      .map(s => {
        // if your DB uses very large ids, consider BigInt handling or string schema
        const n = parseInt(s, 10);
        return Number.isNaN(n) ? null : n;
      })
      .filter(n => n !== null);

    if (productIdInts.length === 0) {
      return json({ error: "No valid product IDs provided" }, { status: 400 });
    }

    // fetch user to get skulimit
    const user = await prisma.users.findUnique({
      where: { id: userId },
      select: { id: true, skuconsumed: true, skulimit: true },
    });

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

 
    // block products
    const updatedProducts = await prisma.products.updateMany({
      where: {
        user_id: userId,
        product_id: { in: productIdInts },
      },
      data: {
        block: false,
      },
    });
    return json({ message: "Products unblocked successfully", updatedCount: updatedProducts.count });

   
  } catch (error) {
    console.error("Count API Error:", error);
    return json({ error: error.message }, { status: 500 });
  }
};
