using LearningMaterialSystem.Data;
using LearningMaterialSystem.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LearningMaterialSystem.Controllers;

[Authorize(Roles = "BoPhanChuyenMon")]
public class ThongKeController : Controller
{
    private readonly ApplicationDbContext _context;

    public ThongKeController(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<IActionResult> Index()
    {
        var vm = new ThongKeViewModel
        {
            TongHocLieu = await _context.HocLieus.CountAsync(),
            TongMonHoc = await _context.MonHocs.CountAsync(),
            TongView = await _context.NhatKyTruyCaps.CountAsync(n => n.HanhDong == "View"),
            TongDownload = await _context.NhatKyTruyCaps.CountAsync(n => n.HanhDong == "Download"),
            TongUpload = await _context.NhatKyTruyCaps.CountAsync(n => n.HanhDong == "Upload")
        };

        vm.TheoHanhDong = await _context.NhatKyTruyCaps
            .GroupBy(n => n.HanhDong)
            .Select(g => new TheoHanhDong { HanhDong = g.Key, SoLuong = g.Count() })
            .ToListAsync();

        var topIds = await _context.NhatKyTruyCaps
            .Where(n => n.HocLieuId != null)
            .GroupBy(n => n.HocLieuId)
            .Select(g => new { HocLieuId = g.Key!.Value, SoLuong = g.Count() })
            .OrderByDescending(x => x.SoLuong)
            .Take(10)
            .ToListAsync();

        var hocLieus = await _context.HocLieus.Where(h => topIds.Select(t => t.HocLieuId).Contains(h.Id))
            .ToDictionaryAsync(h => h.Id, h => h.TieuDe);

        vm.TheoHocLieu = topIds.Select(x => new TheoHocLieu
        {
            HocLieuId = x.HocLieuId,
            TieuDe = hocLieus.GetValueOrDefault(x.HocLieuId, "N/A"),
            SoLuong = x.SoLuong
        }).ToList();

        return View(vm);
    }
}
