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 });
    }

    const countToConsume = productIdInts.length;
    const maxAllowedConsumed = user.skulimit - countToConsume;

    if (maxAllowedConsumed < 0) {
      return json(
        { msg: "Requested import count exceeds your total SKU limit." },
        { status: 403 }
      );
    }

    // atomic increment on user (prevents race)
    const updatedUsers = await prisma.users.updateMany({
      where: {
        id: userId,
      },
      data: {
        skuconsumed: { increment: countToConsume },
      },
    });

    if (updatedUsers.count === 0) {
      return json(
        {
          msg: "You have reached your import limit. Please upgrade your plan to import more products.",
        },
        { status: 403 }
      );
    }

    // Now update products — NOTE: pass integers here
    const updateProducts = await prisma.products.updateMany({
      where: {
        product_id: { in: productIdInts },
      },
      data: {
        status: "Import_in_progress",
      },
    });

    // If you need rollback when no products updated:
    if (updateProducts.count === 0) {
      // rollback user increment (best-effort)
      await prisma.users.update({
        where: { id: userId },
        data: { skuconsumed: { decrement: countToConsume } },
      });

      return json(
        {
          success: false,
          message: "No products for import were found.",
          productsRequested: productIdInts.length,
          productsUpdated: updateProducts.count,
        },
        { status: 404 }
      );
    }

    return json({
      success: true,
      message: "Products import initiated successfully.",
      productsRequested: productIdInts.length,
      productsUpdated: updateProducts.count,
    });
  } catch (error) {
    console.error("Count API Error:", error);
    return json({ error: error.message }, { status: 500 });
  }
};
