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

export const action = async ({ request }) => {
  try {
    const body = await request.json();
    const { data, userId } = body; // data = "priceOnly" | "inventoryOnly" | "syncBoth" | "none"

    let inventory_sync = false;
    let price_sync = false;

    console.log("data    ", data);


    // map selected option to DB values
    switch (data[0]) {
      case "priceOnly":
        price_sync = true;
        break;
      case "inventoryOnly":
        inventory_sync = true;
        break;
      case "syncBoth":
        inventory_sync = true;
        price_sync = true;
        break;
      case "none":
      default:
        // leave both as "0"
        break;
    }

    // check if settings exist
    const existingSetting = await prisma.settings.findFirst({
      where: { user_id: userId },
    });


    if (!existingSetting) {
      await prisma.settings.create({
        data: {
          user_id: userId,
          fulfilment_service: "manual",
          inventory_policy: "continue",
          shopifylocationid: "",
          product_import:false,
          includeoutofstock: false,
          inventory_sync,
          price_sync,
          published: true,
        },
      });
    } else {
      // update existing
      await prisma.settings.update({
        where: { user_id: userId ,id: existingSetting.id},
        data: {
          inventory_sync,
          price_sync,
        },
      });
    }
    await prisma.users.update({
      where: { id: userId },
      data: {
        setup_step: "Done",
      },
    });
    return json({ msg: "Setting Updated", success: true });
  } catch (error) {
    console.error("Error updating settings:", error);
    return json(
      { msg: "Setting Not Updated", success: false },
      { status: 500 },
    );
  }

  async function shopifyGraphQL(query, shopurl, token) {
    const endpoint = `https://${shopurl}/admin/api/2025-07/graphql.json`;

    const response = await fetch(endpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Shopify-Access-Token": token,
      },
      body: JSON.stringify({ query }),
    });

    if (!response.ok) {
      console.error("Shopify API Error:", await response.text());
      throw new Error("Failed to fetch from Shopify API");
    }
    return await response.json();
  }
};
