using Aberwyn.Data;
using Aberwyn.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Globalization;
using System.Linq;

namespace Aberwyn.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly BudgetService _budgetService;

        // Constructor to inject dependencies
        public HomeController(ILogger<HomeController> logger, BudgetService budgetService)
        {
            _logger = logger;
            _budgetService = budgetService;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        public IActionResult RealEstate()
        {
            return View();
        }

        // Optimized Budget Action to fetch filtered data directly from the database
        public IActionResult Budget(string month, int? year)
        {
            // Default to current month and year if parameters are not provided
            int selectedMonth = !string.IsNullOrEmpty(month)
                ? Array.IndexOf(CultureInfo.CurrentCulture.DateTimeFormat.MonthNames, month) + 1
                : DateTime.Now.Month;

            int selectedYear = year ?? DateTime.Now.Year;

            // Fetch budget items for the selected month and year directly from the database
            var budgetItems = _budgetService.GetBudgetItems(selectedMonth, selectedYear);

            // Create the BudgetModel
            var budgetModel = new BudgetModel
            {
                BudgetItems = budgetItems.ToList() // Ensure this is a list
            };

            // Pass the BudgetModel to the view
            return View(budgetModel);
        }


        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
