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

export const action = async ({ request }) => {
  try {
    const { session } = await authenticate.admin(request);
    const body = await request.json();

    console.log("Session:", session?.shop);
    console.log("Received Bodyyy:", body);

    const user = await prisma.users.findFirst({
      where: { shopurl: session.shop },
    });

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

    if (body.userId && !body.data) {
      const settings = await prisma.settings.findFirst({
        where: { user_id: Number(body.userId) },
      });

      if (!settings) {
        return json({ success: false, message: "No settings found", data: null });
      }

      return json({ success: true, message: "Settings found", data: settings });
    }

    if (body.data) {
      const d = body.data;

      const payload = {
        published: d.productSetting === "Active",
        fulfilment_service: d.fulfillmentService,
        inventory_policy: d.inventoryPolicy,
        inventory_sync: d.inSynchronization === "Enable",
        price_sync: d.prSynchronization === "Enable",
        autoimport: d.autoImport === "Enable",
        product_import: true,
        includeoutofstock:false,
        shopifylocationid: '',
      };

      console.log("Prepared payload for DB:", payload);

      const existing = await prisma.settings.findFirst({
        where: { user_id: user.id },
      });

      let result;
      if (existing) {
        result = await prisma.settings.update({
          where: { id: existing.id },
          data: payload,
        });
        console.log("Settings updated:", result);
        return json({ success: true, message: "Settings updated", data: result });
      } else {
     
        result = await prisma.settings.create({
          data: {
            ...payload,
            user_id: user.id,
          },
        });
        console.log("Settings created:", result);
        return json({ success: true, message: "Settings created", data: result });
      }
    }

    return json({ success: false, message: "Invalid request" }, { status: 400 });
  } catch (error) {
    console.error("Settings Action Error:", error);
    return json(
      { success: false, message: "Server error", error: String(error) },
      { status: 500 }
    );
  }
};
