require('dotenv').config();
const fs = require('fs').promises;
const path = require('path');
const connectDB = require('../config/database');

/**
 * Migration: create_complete_blog_system
 * Created: 17:00:00 2/2/2026
 * Description: Tạo hoàn chỉnh hệ thống blog với categories, tags, posts và comments
 */
async function migrate() {
  try {
    // Kết nối database
    await connectDB();
    console.log('🚀 Starting migration: create_complete_blog_system...');
    
    // Import models
    const Blog = require('../models/blog');
    const BlogCategory = require('../models/blogCategory');
    const BlogTag = require('../models/blogTag');
    const BlogComment = require('../models/blogComment');
    const RecentPost = require('../models/recentPost');
    
    console.log('✅ Blog models registered successfully');
    
    // Load complete data
    const dataPath = path.join(__dirname, '..', 'data', 'blog.json');
    const rawData = await fs.readFile(dataPath, 'utf8');
    const data = JSON.parse(rawData);
    
    console.log('📖 Complete blog data loaded from JSON');
    
    // Clear existing data
    console.log('🧹 Clearing existing blog data...');
    await BlogComment.deleteMany({});
    await Blog.deleteMany({});
    await BlogCategory.deleteMany({});
    await BlogTag.deleteMany({});
    await RecentPost.deleteMany({});
    console.log('✅ Existing data cleared');
    
    // 1. Create categories
    console.log('📝 Creating categories...');
    const createdCategories = [];
    for (const categoryData of data.categories) {
      const category = new BlogCategory(categoryData);
      await category.save();
      createdCategories.push(category);
      console.log(`✅ Created category: ${category.name}`);
    }
    
    // 2. Create tags
    console.log('📝 Creating tags...');
    const createdTags = [];
    for (const tagData of data.tags) {
      const tag = new BlogTag(tagData);
      await tag.save();
      createdTags.push(tag);
      console.log(`✅ Created tag: ${tag.name}`);
    }
    
    // 3. Create blog posts
    console.log('📝 Creating blog posts...');
    const createdPosts = [];
    for (const postData of data.posts) {
      const post = new Blog(postData);
      await post.save();
      createdPosts.push(post);
      console.log(`✅ Created blog post: ${post.title}`);
    }
    
    // 4. Create comments
    console.log('💬 Creating comments...');
    let createdCommentsCount = 0;
    
    for (const commentData of data.comments) {
      // Find the blog post by slug
      const blog = await Blog.findOne({ 
        slug: commentData.postSlug, 
        status: 'published' 
      });
      
      if (blog) {
        const comment = new BlogComment({
          postId: blog._id,
          authorName: commentData.authorName,
          authorAvatar: commentData.authorAvatar,
          content: commentData.content,
          createdAt: commentData.createdAt,
          status: commentData.status
        });
        
        await comment.save();
        createdCommentsCount++;
        console.log(`✅ Created comment by ${comment.authorName} for: ${blog.title}`);
      } else {
        console.log(`⚠️  Blog post not found for slug: ${commentData.postSlug}`);
      }
    }
    
    // 5. Update category post counts
    console.log('📊 Updating category post counts...');
    for (const category of createdCategories) {
      await category.updatePostCount();
      console.log(`📊 Category "${category.name}": ${category.postCount} posts`);
    }
    
    // 6. Update tag post counts
    console.log('📊 Updating tag post counts...');
    for (const tag of createdTags) {
      await tag.updatePostCount();
      console.log(`📊 Tag "${tag.name}": ${tag.postCount} posts`);
    }
    
    // 7. Update comments count in blog posts
    console.log('📊 Updating comments count in blog posts...');
    const blogs = await Blog.find({ status: 'published' });
    
    for (const blog of blogs) {
      const commentsCount = await BlogComment.countDocuments({ 
        postId: blog._id, 
        status: 'approved' 
      });
      
      blog.commentsCount = commentsCount;
      await blog.save();
      
      if (commentsCount > 0) {
        console.log(`📊 Updated comments count for "${blog.title}": ${commentsCount} comments`);
      }
    }
    
    // 8. Sync recent posts
    console.log('🔄 Syncing recent posts...');
    await RecentPost.syncFromBlogs(5);
    const recentPostsCount = await RecentPost.countDocuments();
    console.log(`🔄 Synced ${recentPostsCount} recent posts`);
    
    // Final summary
    console.log('\n🎉 Migration create_complete_blog_system completed successfully!');
    console.log('=' .repeat(60));
    console.log('📊 MIGRATION SUMMARY:');
    console.log(`   ✅ Categories: ${createdCategories.length}`);
    console.log(`   ✅ Tags: ${createdTags.length}`);
    console.log(`   ✅ Blog Posts: ${createdPosts.length}`);
    console.log(`   ✅ Comments: ${createdCommentsCount}`);
    console.log(`   ✅ Recent Posts: ${recentPostsCount}`);
    
    // Statistics
    const totalPublishedPosts = await Blog.countDocuments({ status: 'published' });
    const totalFeaturedPosts = await Blog.countDocuments({ status: 'published', isFeatured: true });
    const totalApprovedComments = await BlogComment.countDocuments({ status: 'approved' });
    
    console.log('\n📈 SYSTEM STATISTICS:');
    console.log(`   📝 Published Posts: ${totalPublishedPosts}`);
    console.log(`   ⭐ Featured Posts: ${totalFeaturedPosts}`);
    console.log(`   💬 Approved Comments: ${totalApprovedComments}`);
    
    console.log('\n🌐 ACCESS POINTS:');
    console.log('   📱 Admin Panel: http://localhost:3001/admin/blog');
    console.log('   🔗 API Endpoint: http://localhost:3001/api/blog');
    console.log('   📊 Categories API: http://localhost:3001/api/blog-categories');
    console.log('   🏷️  Tags API: http://localhost:3001/api/blog-tags');
    
    console.log('\n✨ Blog system is now ready for use!');
    console.log('=' .repeat(60));
    
    const mongoose = require('mongoose');
    await mongoose.disconnect();
    process.exit(0);
  } catch (error) {
    console.error('❌ Migration error:', error);
    process.exit(1);
  }
}

// Chạy migration nếu được gọi trực tiếp
if (require.main === module) {
  migrate();
}

module.exports = { migrate };