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

    // validate userId
    const userId = parseInt(userIdRaw, 10);
    if (!userIdRaw || Number.isNaN(userId)) {
      return json({ error: "Invalid or missing userId" }, { 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 countOfProduct  = await prisma.products.count({
      where: { user_id: userId, status: "Ready_to_Import" },
    });

    const maxAllowedConsumed = user.skulimit - countOfProduct + user.skuconsumed;

    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.update({
      where: {
        id: userId,
      },
      data: {
        skuconsumed: { increment: countOfProduct },
      },
    });

    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: {
        user_id: userId,
        status: "Ready_to_Import",
        block:false
      },
      data: {
        status: "Import_in_progress",
      },
    });

    // If you need rollback when no products updated:
    if (updateProducts.count === 0) {
      // rollback user increment (best-effort)
  

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

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