import prisma from "./app/db.server";
import { parseWidgetSettings } from "./app/services/widget-settings.server";

async function main() {
  const shops = await prisma.shop.findMany({
    include: {
      chatbotSettings: true,
      subscriptions: {
        where: { status: "ACTIVE" },
        orderBy: { createdAt: "desc" },
        take: 1,
      },
    },
    orderBy: { createdAt: "desc" },
  });

  console.log(`\n======================================================`);
  console.log(`  INSTALLED SHOPS & CHATBOT STATUS OVERVIEW (${shops.length} Stores)`);
  console.log(`======================================================\n`);

  for (const shop of shops) {
    const settings = shop.chatbotSettings;
    const { widgetTexts } = parseWidgetSettings(settings);
    const isChatbotAdminDisabled = widgetTexts.adminDisabled === true;
    const isChatbotEnabled = settings?.enabled ?? true;
    const activeSub = shop.subscriptions[0];

    const statusDisplay = isChatbotAdminDisabled
      ? "🚫 INACTIVE (Locked by SaaS Admin)"
      : isChatbotEnabled
      ? "✓ ACTIVE (Visible on Storefront)"
      : "⏸ INACTIVE (Hidden by Merchant)";

    console.log(`Store Domain:       ${shop.shopifyDomain}`);
    console.log(`Store ID:           ${shop.id}`);
    console.log(`Shop Status:        ${shop.uninstalledAt ? "UNINSTALLED" : "ACTIVE"}`);
    console.log(`Current Plan:       ${activeSub?.plan || "FREE"}`);
    console.log(`Chatbot Status:     ${statusDisplay}`);
    console.log(`  - Admin Disabled: ${isChatbotAdminDisabled}`);
    console.log(`  - Merchant Enable: ${isChatbotEnabled}`);
    console.log(`  - Bot Name:       ${widgetTexts.botName || settings?.botName || "ShopPilot AI Assistant"}`);
    console.log(`  - Primary Color:  ${settings?.primaryColor || "#4F46E5"}`);
    console.log(`  - Position:       ${settings?.position || "bottom-right"}`);
    console.log(`------------------------------------------------------\n`);
  }
}

main()
  .catch((err) => {
    console.error("Error inspecting database:", err);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
