import prisma from "../db.server";
import { encryptToken, decryptToken } from "../lib/security/encryption";

export interface RegisterShopParams {
  shopifyDomain: string;
  shopifyShopId?: string;
  accessToken: string;
  refreshToken?: string;
  tokenExpiresAt?: Date;
  scopes: string;
  isReinstall?: boolean;
}

/**
 * Registers or updates a multi-tenant Shop record with AES-256 encrypted tokens.
 */
export async function registerShop(params: RegisterShopParams) {
  const normalizedDomain = params.shopifyDomain.toLowerCase().trim();
  const existingShop = await prisma.shop.findUnique({ where: { shopifyDomain: normalizedDomain } });

  const shouldUpdateToken = params.accessToken !== "shpss_sample_token" || !existingShop;
  const encryptedToken = shouldUpdateToken ? encryptToken(params.accessToken) : existingShop.accessToken;
  const encryptedRefreshToken = params.refreshToken ? encryptToken(params.refreshToken) : (existingShop?.refreshToken || null);

  // Preserve existing uninstalledAt status unless explicitly marked as reinstall
  const uninstalledAt = params.isReinstall ? null : (existingShop?.uninstalledAt ?? null);

  const shop = await prisma.shop.upsert({
    where: { shopifyDomain: normalizedDomain },
    update: {
      shopifyShopId: params.shopifyShopId || existingShop?.shopifyShopId,
      accessToken: encryptedToken,
      refreshToken: encryptedRefreshToken,
      tokenExpiresAt: params.tokenExpiresAt || existingShop?.tokenExpiresAt,
      scopes: params.scopes,
      uninstalledAt,
      updatedAt: new Date(),
    },
    create: {
      shopifyDomain: normalizedDomain,
      shopifyShopId: params.shopifyShopId,
      accessToken: encryptedToken,
      refreshToken: encryptedRefreshToken,
      tokenExpiresAt: params.tokenExpiresAt,
      scopes: params.scopes,
    },
  });

  // Ensure default ChatbotSettings record exists
  await prisma.chatbotSettings.upsert({
    where: { shopId: shop.id },
    update: {},
    create: {
      shopId: shop.id,
      botName: "ConverseCart Assistant",
      welcomeMessage: "Hi 👋 How can I help you find products or track orders today?",
      primaryColor: "#4F46E5",
      secondaryColor: "#4338CA",
      textColor: "#FFFFFF",
      botTextColor: "#1F2937",
      showPoweredBy: true,
      position: "bottom-right",
      enabled: true,
      model: "gpt-4o-mini",
    },
  });

  // Ensure default SystemIntegration record exists in dedicated system_integrations table
  await prisma.systemIntegration.upsert({
    where: { id: "global" },
    update: {},
    create: {
      id: "global",
      aiProvider: "openai",
      openaiModel: "gpt-4o-mini",
      openaiTemperature: 0.7,
      openaiMaxTokens: 1000,
      openaiEnabled: true,
      geminiModel: "gemini-1.5-flash",
      geminiTemperature: 0.7,
      geminiMaxTokens: 1000,
      geminiEnabled: true,
    },
  });

  // Ensure default Subscription (FREE plan) exists
  await prisma.subscription.upsert({
    where: { id: `sub_${shop.id}` },
    update: {},
    create: {
      id: `sub_${shop.id}`,
      shopId: shop.id,
      plan: "FREE",
      status: "ACTIVE",
      monthlyLimit: 100,
      currentUsage: 0,
      billingPeriodStart: new Date(),
      billingPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
    },
  });

  return shop;
}

/**
 * Gets a Shop and returns the decrypted access token.
 */
export async function getShopWithDecryptedToken(shopifyDomain: string) {
  const normalizedDomain = shopifyDomain.toLowerCase().trim();
  const shop = await prisma.shop.findUnique({
    where: { shopifyDomain: normalizedDomain },
  });

  if (!shop) return null;

  return {
    ...shop,
    decryptedAccessToken: decryptToken(shop.accessToken),
    decryptedRefreshToken: shop.refreshToken ? decryptToken(shop.refreshToken) : null,
  };
}
