// const { getUnFulfilledOrders } = require("../services/shopifyService");
const { exec } = require("child_process");
const { promisify } = require("util");
const cron = require("node-cron");
const { customer } = require("../models");

const execPromise = promisify(exec);
const API_KEY = "65c3c809c002379e3a0ea04aeaf2cf84";
const API_PASSWORD = "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";
const STORE = "roving-house.myshopify.com";
const API_VERSION = "2022-01";

// (async () => {
//   const orders = await getUnFulfilledOrders();
//   console.log(orders);
// })();

async function fetchShopifyCustomers() {
  let nextUrl = `https://${API_KEY}:${API_PASSWORD}@${STORE}/admin/api/${API_VERSION}/customers.json?limit=250`;
  const allCustomers = [];

  try {
    while (nextUrl) {
      const curlCommand = `curl -i -X GET "${nextUrl}"`;
      const { stdout } = await execPromise(curlCommand);

      console.log(stdout);

      // Separate headers and body
      const parts = stdout.split("\r\n\r\n");
      const rawHeaders = parts[0];
      const body = parts.slice(1).join("\r\n\r\n");

      const response = JSON.parse(body);
      if (response.customers) {
        allCustomers.push(...response.customers);
      }

      // console.log(response);

      // Parse pagination header
      const match = rawHeaders.match(/<([^>]+)>; rel="next"/);
      nextUrl = match ? match[1] : null;
    }

    return allCustomers;
  } catch (error) {
    console.error("Error fetching customers:", error);
    throw error;
  }
}

async function syncCustomers() {
  try {
    const shopifyCustomers = await fetchShopifyCustomers();
    console.log(`Found ${shopifyCustomers.length} customers from Shopify`);

    for (const c of shopifyCustomers) {
      await customer.findOrCreate({
        where: { shopify_customer_id: c.id.toString() },
        defaults: {
          shopify_customer_id: c.id.toString(),
          shopify_customer_email: c.email || "",
        },
      });
      console.log(`Created customer: ${c.id}`);
    }

    console.log("Customer sync completed successfully");
  } catch (error) {
    console.error("Customer sync failed:", error);
  }
}

syncCustomers();

// run every minute
// cron.schedule("* * * * *", () => {
//   console.log("Running Shopify customer sync...");
//   syncCustomers();
// });

// For manual testing
module.exports = { syncCustomers };
