import "@shopify/shopify-app-remix/adapters/node";
import {
  ApiVersion,
  AppDistribution,
  shopifyApp,
} from "@shopify/shopify-app-remix/server";
import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma";
import prisma from "./db.server";

const shopify = shopifyApp({
  apiKey: process.env.SHOPIFY_API_KEY,
  apiSecretKey: process.env.SHOPIFY_API_SECRET || "",
  apiVersion: ApiVersion.January25,
  scopes: process.env.SCOPES?.split(","),
  appUrl: process.env.SHOPIFY_APP_URL || "",
  authPathPrefix: "/auth",
  sessionStorage: new PrismaSessionStorage(prisma),
  distribution: AppDistribution.AppStore,
  future: {
    unstable_newEmbeddedAuthStrategy: true,
    removeRest: true,
  },
  ...(process.env.SHOP_CUSTOM_DOMAIN
    ? { customShopDomains: [process.env.SHOP_CUSTOM_DOMAIN] }
    : {}),
     hooks: {
    afterAuth: async ({ session, admin }) => {
      try {
        await shopify.registerWebhooks({ session });
        console.log("Webhooks registered successfully for", session.shop);
      } catch (error) {
        console.error("Error registering webhooks for", session.shop, error);
      }
      await userInsert(session,admin);
      return new Response(null, {
        status: 302,
        headers: {
          Location: `/app?shop=${session.shop}`,
        },
      });
    },
  },
});
function randomString(length = 10) {
  return Math.random().toString(36).substring(2, 2 + length);
}

// console.log(randomString(12));

const userInsert =async (session,admin)=>{
      try {
        let user = await prisma.users.findFirst({
          where: { shopurl: session.shop }
        });
        if (!user) {
          const shopQuery = `
              {
              shop {
                id
                name
                createdAt
                updatedAt
                shopOwnerName
                email
                plan {
                  displayName
                  partnerDevelopment
                  shopifyPlus
                }
              }
            }
          `;
       
          const shopResponse = await admin.graphql(shopQuery);
          const shopData = await shopResponse.json();
          let tempcode = randomString(10);
           user = await prisma.users.create({
              data: {
                ownername: shopData.data.shop.shopOwnerName,
                email: shopData.data.shop.email,
                password: "",
                avatar_url: "",
                shopurl: session.shop,
                token: session.accessToken,
                status: "active",
                catalogfetched: 0,
                shopifyimported: 0,
                tempcode: tempcode,
                usermsg:"",
                review:0,
                discount:0.0,     
                installationstatus: 1,
                membershiptype: "free",
                plan: 0,
                sync: 0,
                storecreated_at: new Date(),
                storeupdated_at: new Date(),
                created_at:new Date(),
                updated_at:new Date(),
                plan_name: "Free",
                skulimit: 5,
                skuconsumed: 0,
                tosaccepted: 0,
                publishstatus: 0,
                keysemail: 0,
                wmfetched:false,
                ebfetched:false,
                fbainvnt:0,
                includeoutofstock:0,
                includesaleprice:false,
                ebtoken:false,
              },
            });
            localStorage.setItem('setup','first');
            console.log("now step is first");
          // console.log("New user created:", user.id, "for shop:", session.shop);
         
        } else {
          await prisma.users.update({
            where: { id: user.id },
            data: {
              token: session.accessToken,
              installationstatus: 1
            }
          });
          console.log("User token updated for existing user:", user.id);
          localStorage.setItem('setup',user.setup_step);
        }
      } catch (error) {
        console.error("Error handling user data for", session.shop, error);
      }
}

export default shopify;
export const apiVersion = ApiVersion.January25;
export const addDocumentResponseHeaders = shopify.addDocumentResponseHeaders;
export const authenticate = shopify.authenticate;
export const unauthenticated = shopify.unauthenticated;
export const login = shopify.login;
export const registerWebhooks = shopify.registerWebhooks;
export const sessionStorage = shopify.sessionStorage;
