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

    // check user in queue: look for any request for this user whose status is NOT "readyforshopify"
    const existingRequest = await prisma.amz_reportrequests.findFirst({
      where: {
        user_id: userId,
        status: { not: "readyforshopify" }, // <-- fixed syntax
      },
      orderBy: { created_at: "desc" },
    });

    if (existingRequest) {
      return json(
        { msg: "A fetch request is already pending." },
        { status: 202 } // conflict
      );
    }

    await prisma.amz_reportrequests.create({
      data: {
        user_id: userId,
        status: "pending",
        requestid:"", // placeholder, to be updated later
        reportid:"", // placeholder, to be updated later
        inprocess:false,
        reporttype:"_GET_MERCHANT_LISTINGS_DATA_"
      },
    });

    return json(
      { msg: "Product fetch request submitted successfully." },
      { status: 201 }
    );
  } catch (error) {
    console.error("Count API Error:", error);
    return json({ error: error.message }, { status: 500 });
  }
};
