require("dotenv").config();
const fs = require("fs").promises;
const path = require("path");
const mongoose = require("mongoose");

const connectDB = require("../config/database");
const Service = require("../models/service");

/**
 * Transform service.json data to match Service schema
 */
function transformServiceData(sourceData) {
  return {
    pageTitle: sourceData.pageTitle || "",

    // Breadcrumb navigation section
    breadcrumb: {
      title: sourceData?.breadcrumb?.title || "",
      backgroundImage: sourceData?.breadcrumb?.backgroundImage || "",
      shape: sourceData?.breadcrumb?.shape || "",
      items: Array.isArray(sourceData?.breadcrumb?.items)
        ? sourceData.breadcrumb.items.map((item) => ({
            label: item.label || "",
            href: item.href || "",
          }))
        : [],
    },

    // Main services section
    services: {
      title: {
        subTitle: sourceData?.services?.title?.subTitle || "",
        mainTitle: sourceData?.services?.title?.mainTitle || "",
      },
      items: Array.isArray(sourceData?.services?.items)
        ? sourceData.services.items.map((service) => ({
            slug: service.slug || "",
            name: service.name || "",
            description: service.description || "",
            image: service.image || "",
            layout: service.layout || "",
            details: {
              title: service.details?.title || "",
              description: service.details?.description || "",
              mainImage: service.details?.mainImage || "",
              overviewTitle: service.details?.overviewTitle || "",
              overviewDescription: service.details?.overviewDescription || "",
              additionalDescription:
                service.details?.additionalDescription || "",
              keyFeaturesTitle: service.details?.keyFeaturesTitle || "",
              keyFeaturesImage: service.details?.keyFeaturesImage || "",
              features: Array.isArray(service.details?.features)
                ? service.details.features.map((feature) => ({
                    icon: feature.icon || "",
                    title: feature.title || "",
                    description: feature.description || "",
                  }))
                : [],
              faqTitle: service.details?.faqTitle || "",
              faqImage: service.details?.faqImage || "",
              faq: Array.isArray(service.details?.faq)
                ? service.details.faq.map((faqItem) => ({
                    id: faqItem.id || "",
                    question: faqItem.question || "",
                    answer: faqItem.answer || "",
                    isExpanded: faqItem.isExpanded || false,
                  }))
                : [],
            },
          }))
        : [],
    },

    // Destination countries section
    destinations: {
      backgroundImage: sourceData?.destinations?.backgroundImage || "",
      title: {
        subTitle: sourceData?.destinations?.title?.subTitle || "",
        mainTitle: sourceData?.destinations?.title?.mainTitle || "",
      },
      items: Array.isArray(sourceData?.destinations?.items)
        ? sourceData.destinations.items.map((country) => ({
            id: country.id || "",
            name: country.name || "",
            description: country.description || "",
            image: country.image || "",
            icon: country.icon || "",
            link: country.link || "",
          }))
        : [],
    },

    // Visa types section
    visas: {
      items: Array.isArray(sourceData?.visas?.items)
        ? sourceData.visas.items.map((visa) => ({
            id: visa.id || "",
            number: visa.number || "",
            name: visa.name || "",
            description: visa.description || "",
            buttonText: visa.buttonText || "",
            buttonLink: visa.buttonLink || "",
          }))
        : [],
    },

    // Client reviews section
    reviews: {
      title: {
        subTitle: sourceData?.reviews?.title?.subTitle || "",
        mainTitle: sourceData?.reviews?.title?.mainTitle || "",
      },
      viewAllButton: {
        text: sourceData?.reviews?.viewAllButton?.text || "",
        icon: sourceData?.reviews?.viewAllButton?.icon || "",
        link: sourceData?.reviews?.viewAllButton?.link || "",
      },
      thumb: sourceData?.reviews?.thumb || "",
      items: Array.isArray(sourceData?.reviews?.items)
        ? sourceData.reviews.items.map((review) => ({
            id: review.id || "",
            rating: review.rating || 5,
            content: review.content || "",
            author: {
              name: review.author?.name || "",
              type: review.author?.type || "",
            },
            icon: review.icon || "",
          }))
        : [],
      navigation: {
        prevButton: sourceData?.reviews?.navigation?.prevButton || "",
        nextButton: sourceData?.reviews?.navigation?.nextButton || "",
        prevIcon: sourceData?.reviews?.navigation?.prevIcon || "",
        nextIcon: sourceData?.reviews?.navigation?.nextIcon || "",
      },
    },

    updatedAt: new Date(),
  };
}

/**
 * Migration function for service page data
 */
async function migrateServiceData() {
  try {
    await connectDB();
    console.log("🚀 Starting service page migration...");

    // Clear existing service documents
    await Service.deleteMany({});
    console.log("🗑️ Cleared existing service documents");

    // Read service.json file
    const serviceJsonPath = path.join(__dirname, "..", "data", "service.json");
    const rawJsonData = await fs.readFile(serviceJsonPath, "utf8");
    const sourceServiceData = JSON.parse(rawJsonData);

    // Transform data to match schema
    const transformedServiceData = transformServiceData(sourceServiceData);

    // Create new service document
    const newService = new Service(transformedServiceData);
    const savedService = await newService.save();

    console.log("✅ Service page migration completed successfully!");
    console.log(`📄 Service document ID: ${savedService._id}`);

    await mongoose.disconnect();
    process.exit(0);
  } catch (error) {
    console.error("❌ Service migration error:", error);
    process.exit(1);
  }
}

// Run migration if called directly
if (require.main === module) {
  migrateServiceData();
}

module.exports = {
  migrate: migrateServiceData,
  transformServiceData,
};
