const mongoose = require("mongoose");

// Schema cho content items
const contentItemSchema = new mongoose.Schema(
  {
    type: {
      type: String,
      enum: ["paragraph", "section", "list", "note", "embed", "header"],
      required: true,
    },
    text: {
      type: String,
      trim: true,
      default: "",
    },
    title: {
      type: String,
      trim: true,
      default: "",
    },
    content: {
      type: String,
      trim: true,
      default: "",
    },
    items: {
      type: [String],
      default: [],
    },
    level: {
      type: Number,
      default: 2,
    },
    // Embed/video fields
    embed: {
      type: String,
      trim: true,
      default: ''
    },
    url: {
      type: String,
      trim: true,
      default: ''
    },
    source: {
      type: String,
      trim: true,
      default: ''
    },
    videoId: {
      type: String,
      trim: true,
      default: ''
    },
    caption: {
      type: String,
      trim: true,
      default: ''
    },
    width: {
      type: Number,
      default: 0
    },
    height: {
      type: Number,
      default: 0
    },
  },
  { _id: false }
);

// Schema cho overlay style
const overlayStyleSchema = new mongoose.Schema(
  {
    backgroundColor: {
      type: String,
      trim: true,
      default: "rgba(0, 0, 0, 0)",
    },
  },
  { _id: false }
);

// Schema cho hero section
const heroSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
      trim: true,
      default: "Insurance & Travel Cancellation Guarantee",
    },
    subtitle: {
      type: String,
      trim: true,
      default: "Comprehensive coverage for your peace of mind",
    },
    backgroundImage: {
      type: String,
      trim: true,
      default: "/uploads/banner/b13.jpg",
    },
    sectionClass: {
      type: String,
      trim: true,
      default: "uk-section-default uk-section-overlap uk-preserve-color uk-light uk-position-relative",
    },
    backgroundClasses: {
      type: String,
      trim: true,
      default: "uk-background-norepeat uk-background-cover uk-background-top-center uk-section uk-section-xlarge",
    },
    overlayStyle: {
      type: overlayStyleSchema,
      default: () => ({ backgroundColor: "rgba(0, 0, 0, 0)" }),
    },
    titleClass: {
      type: String,
      trim: true,
      default: "text-white text-[5vw] uk-text-center",
    },
    subtitleClass: {
      type: String,
      trim: true,
      default: "uk-panel font-[Raleway] italic text-[1.5vw] uk-margin uk-text-center",
    },
    enableScrollspy: {
      type: Boolean,
      default: true,
    },
  },
  { _id: false }
);

// Schema cho page section
const pageSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
      trim: true,
      default: "Insurance & Travel Information",
    },
    divider: {
      type: Boolean,
      default: true,
    },
    sectionClass: {
      type: String,
      trim: true,
      default: "uk-section-default uk-section-overlap uk-section",
    },
    titleClass: {
      type: String,
      trim: true,
      default: "text-[2.5vw] text-[#292c3d] uk-text-left@m uk-text-center",
    },
    dividerClass: {
      type: String,
      trim: true,
      default: "uk-divider-small uk-text-left@m uk-text-center",
    },
  },
  { _id: false }
);

// Schema cho content section
const contentSchema = new mongoose.Schema(
  {
    sectionClass: {
      type: String,
      trim: true,
      default: "uk-section-muted uk-section-overlap uk-section",
    },
    textClass: {
      type: String,
      trim: true,
      default: "uk-panel uk-margin text-[1vw]",
    },
    content: {
      type: [contentItemSchema],
      default: [],
    },
  },
  { _id: false }
);

// Main Insurance Schema - CẤU TRÚC MỚI
const insuranceSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      default: "default",
      unique: true,
    },
    // 3 PHẦN CHÍNH
    hero: {
      type: heroSchema,
      required: true,
    },
    page: {
      type: pageSchema,
      required: true,
    },
    content: {
      type: contentSchema,
      required: true,
    },
    language: {
      type: String,
      default: "en",
    },
    version: {
      type: String,
      default: "2.0.0",
    },
    isActive: {
      type: Boolean,
      default: true,
    },
    migratedFromOldStructure: {
      type: Boolean,
      default: false,
    },
  },
  {
    timestamps: true,
  }
);

// Static method: Lấy insurance default
insuranceSchema.statics.getDefault = async function(language = "en") {
  try {
    let insurance = await this.findOne({ name: "default", language: language });
    
    if (!insurance) {
      // Tạo default data nếu chưa có
      insurance = await this.create({
        name: "default",
        language: language,
        hero: {
          title: "Insurance & Travel Cancellation Guarantee",
          subtitle: "Comprehensive coverage for your peace of mind",
          backgroundImage: "/uploads/banner/b13.jpg",
        },
        page: {
          title: "Insurance & Travel Information",
          divider: true,
        },
        content: {
          content: []
        }
      });
    }
    
    return insurance;
  } catch (error) {
    console.error("Error in getDefault:", error);
    throw error;
  }
};

// Method để get insurance data
insuranceSchema.methods.getInsuranceData = function() {
  return this.toObject();
};

// Migration method - chỉ hỗ trợ cấu trúc mới
insuranceSchema.statics.migrateFromJson = async function(jsonData, language = "en") {
  try {
    console.log('Migrating insurance from JSON...');
    
    // Xóa document cũ nếu có
    await this.deleteOne({ name: "default", language: language });
    
    // Sử dụng dữ liệu từ JSON trực tiếp
    const processedData = {
      name: "default",
      language: language,
      version: "2.0.0",
      isActive: true,
      hero: jsonData.hero,
      page: jsonData.page,
      content: jsonData.content
    };
    
    // Tạo document mới
    const newInsurance = await this.create(processedData);
    const contentItems = jsonData.content?.content || [];
    console.log(`Insurance data migrated successfully for language: ${language}`);
    console.log(`Total content items: ${contentItems.length}`);
    
    return newInsurance;
  } catch (error) {
    console.error("Error migrating insurance data to new structure:", error);
    throw error;
  }
};

const Insurance = mongoose.model("Insurance", insuranceSchema);

module.exports = Insurance;
