"use server";

import { prisma } from "@/lib/prisma";
import bcrypt from "bcryptjs";
import { machineIdSync } from "node-machine-id";

export async function setupSystem(formData: any) {
  try {
    const staffCount = await prisma.staff.count();
    if (staffCount > 0) {
      return { success: false, error: "سیستم قبلاً نصب شده است." };
    }

    // 1. Verify License against Tukan Hub
    // In production this URL will be env variable e.g. https://hub.tukanco.ir/api/verify
    const HUB_URL = process.env.HUB_URL || "https://hub.qocteam.com";
    const phone = formData.phone || "09000000000";
    
    // Grab Windows/Hardware ID
    const hardwareId = machineIdSync(true);

    const verifyRes = await fetch(`${HUB_URL}/api/verify`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ adminPhone: phone, machineId: hardwareId }),
    }).catch(() => null);

    if (!verifyRes) {
      return { success: false, error: "خطا در ارتباط با سرور مرکزی لایسنس (ارتباط اینترنتی را چک کنید)." };
    }

    const licenseData = await verifyRes.json();
    if (!licenseData.success) {
      return { success: false, error: licenseData.reason || "شما دارای لایسنس فعال در سیستم توکان نیستید." };
    }

    await prisma.$transaction(async (tx) => {
      // 2. Create Admin Staff
      const hashedPassword = await bcrypt.hash(formData.password, 10);
      await tx.staff.create({
        data: {
          fullName: `${formData.firstName} ${formData.lastName}`,
          username: formData.username,
          passwordHash: hashedPassword,
          phone: phone,
          role: "ADMIN",
          isActive: true
        }
      });

      // 3. Create Settings (Now with Tamper-Proof License Token Data)
      await tx.setting.deleteMany({});
      await tx.setting.create({
        data: {
          siteName: licenseData.clientName || formData.storeName,
          phone: formData.storePhone,
          address: formData.storeAddress,
          storefrontHeaderTitle: licenseData.clientName || formData.storeName,
          storefrontHeaderSubtitle: "فروشگاه آنلاین ما",
          logoUrl: formData.logoUrl || null,
          licenseToken: licenseData.licenseToken,
          licenseValidUntil: new Date(licenseData.rawExpiration)
        }
      });

      // 5. Create Bank Accounts and PosTerminals
      if (formData.accounts) {
        const accountsData = JSON.parse(formData.accounts);
        for (const account of accountsData) {
          const { id, terminals, ...accountDetails } = account;
          await tx.bankAccount.create({
            data: {
              ...accountDetails,
              balance: parseInt(accountDetails.balance) || 0,
              terminals: {
                create: terminals?.map((t: any) => ({
                  name: t.name,
                  type: t.type
                })) || []
              }
            }
          });
        }
      } else {
        await tx.bankAccount.create({
          data: { name: "صندوق نقدی (پیش‌فرض)", bankName: "صندوق فروشگاه", type: "CASH", balance: 0 }
        });
      }

      // 6. Create Initial Storefront Pages
      const emptyContent = JSON.stringify({ sections: [] });
      const pages = [
        {
          title: 'صفحه اصلی فروشگاه', slug: 'home', type: 'HOME',
          content: JSON.stringify({
            sections: [
              {
                id: "sec_hero", settings: { padding: "py-16" },
                columns: [
                  {
                    id: "col_hero", span: "col-span-12",
                    elements: [
                      { id: "el_hero_heading", type: "heading", props: { text: "به فروشگاه آنلاین ما خوش آمدید", tag: "h1", className: "text-4xl font-black text-center mb-4 text-indigo-600" } },
                      { id: "el_hero_desc", type: "text", props: { text: "بهترین محصولات را با بالاترین کیفیت و سریع‌ترین ارسال از ما بخواهید.", className: "text-lg text-center text-muted-foreground max-w-2xl mx-auto" } }
                    ]
                  }
                ]
              },
              {
                id: "sec_products", settings: { padding: "py-8" },
                columns: [
                  {
                    id: "col_products", span: "col-span-12",
                    elements: [
                      { id: "el_prod_slider", type: "product_slider", props: { displayType: "slider", sortBy: "newest", blockTitle: "جدیدترین محصولات", blockTitleColor: "#4f46e5", blockIconBgColor: "#e0e7ff" } }
                    ]
                  }
                ]
              }
            ]
          })
        },
        { title: 'درباره ما', slug: 'about', type: 'STATIC', content: emptyContent },
        { title: 'تماس با ما', slug: 'contact', type: 'STATIC', content: emptyContent },
        { title: 'پروفایل کاربری', slug: 'profile', type: 'USER_PROFILE', content: emptyContent },
        { title: 'سبد خرید', slug: 'cart', type: 'CART', content: emptyContent },
        { title: 'تسویه حساب', slug: 'checkout', type: 'CHECKOUT', content: emptyContent },
        { title: 'برگه عمومی محصولات', slug: 'product-single', type: 'PRODUCT_SINGLE', content: emptyContent },
        { title: 'برگه عمومی دسته‌بندی', slug: 'category-archive', type: 'CATEGORY_ARCHIVE', content: emptyContent },
        { title: 'جستجو', slug: 'search', type: 'SEARCH', content: emptyContent },
      ];

      for (const p of pages) {
        await tx.storePage.create({
          data: {
            title: p.title,
            slug: p.slug,
            type: p.type,
            content: p.content,
            isPublished: true,
          }
        });
      }
      
      // 7. Create Default Menu
      await tx.storeMenu.create({
        data: {
          name: "منوی اصلی وبسایت",
          position: "HEADER",
          items: JSON.stringify([
            { id: "home", label: "صفحه اصلی", link: "/" },
            { id: "products", label: "محصولات", link: "/products" },
            { id: "contact", label: "تماس با ما", link: "/contact" }
          ])
        }
      });

    });

    return { success: true };
  } catch (error: any) {
    console.error("Setup error:", error);
    return { success: false, error: "خطا در راه‌اندازی سیستم: " + error.message };
  }
}
