using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using LittleShop.Services;

namespace LittleShop.Areas.Admin.Controllers;

[Area("Admin")]
[Authorize(Policy = "AdminOnly")]
public class DashboardController : Controller
{
    private readonly IOrderService _orderService;
    private readonly IProductService _productService;
    private readonly ICategoryService _categoryService;

    public DashboardController(
        IOrderService orderService,
        IProductService productService,
        ICategoryService categoryService)
    {
        _orderService = orderService;
        _productService = productService;
        _categoryService = categoryService;
    }

    public async Task<IActionResult> Index()
    {
        var orders = await _orderService.GetAllOrdersAsync();
        var products = await _productService.GetAllProductsAsync();
        var categories = await _categoryService.GetAllCategoriesAsync();

        // Basic metrics
        ViewData["TotalOrders"] = orders.Count();
        ViewData["TotalProducts"] = products.Count();
        ViewData["TotalCategories"] = categories.Count();
        ViewData["TotalRevenue"] = orders.Where(o => o.PaidAt.HasValue).Sum(o => o.TotalAmount).ToString("F2");

        // Enhanced metrics
        ViewData["TotalVariations"] = products.Sum(p => p.Variations.Count);
        ViewData["PendingOrders"] = orders.Count(o => o.Status == LittleShop.Enums.OrderStatus.PendingPayment);
        ViewData["ShippedOrders"] = orders.Count(o => o.Status == LittleShop.Enums.OrderStatus.Shipped);
        ViewData["TotalStock"] = products.Sum(p => p.StockQuantity);
        ViewData["LowStockProducts"] = products.Count(p => p.StockQuantity < 10);
        ViewData["OutOfStockProducts"] = products.Count(p => p.StockQuantity == 0);

        // Recent activity
        ViewData["RecentOrders"] = orders.OrderByDescending(o => o.CreatedAt).Take(5);
        ViewData["TopProducts"] = products.OrderByDescending(p => p.StockQuantity).Take(5);

        return View();
    }
}