using Microsoft.AspNetCore.Mvc;
using SkyArtShop.Models;
using SkyArtShop.Services;

namespace SkyArtShop.Controllers
{
    public class HomeController : Controller
    {
        private readonly MongoDBService _mongoService;
        private readonly string _settingsCollection = "SiteSettings";
        private readonly string _productsCollection = "Products";
        private readonly string _sectionsCollection = "HomepageSections";

        public HomeController(MongoDBService mongoService)
        {
            _mongoService = mongoService;
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public async Task<IActionResult> Index()
        {
            var settings = await GetSiteSettings();
            var topProducts = await GetTopSellerProducts();
            var sections = await GetHomepageSections();
            
            ViewBag.Settings = settings;
            ViewBag.TopProducts = topProducts;
            ViewBag.Sections = sections;
            
            return View();
        }

        private async Task<SiteSettings> GetSiteSettings()
        {
            var settingsList = await _mongoService.GetAllAsync<SiteSettings>(_settingsCollection);
            return settingsList.FirstOrDefault() ?? new SiteSettings();
        }

        private async Task<List<Product>> GetTopSellerProducts()
        {
            var products = await _mongoService.GetAllAsync<Product>(_productsCollection);
            return products.Where(p => p.IsTopSeller && p.IsActive).Take(4).ToList();
        }

        private async Task<List<HomepageSection>> GetHomepageSections()
        {
            var sections = await _mongoService.GetAllAsync<HomepageSection>(_sectionsCollection);
            Console.WriteLine($"Total sections from DB: {sections.Count}");
            var activeSections = sections.Where(s => s.IsActive).OrderBy(s => s.DisplayOrder).ToList();
            Console.WriteLine($"Active sections: {activeSections.Count}");
            foreach (var section in activeSections)
            {
                Console.WriteLine($"Section: {section.Title} | Type: {section.SectionType} | Order: {section.DisplayOrder} | Active: {section.IsActive}");
            }
            return activeSections;
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View();
        }
    }
}
