using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
using Watcher.Data;
using Watcher.Models;
using Watcher.ViewModels;

namespace Watcher.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private readonly AppDbContext _context;

        public HomeController(AppDbContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> Index()
        {
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

            var user = await _context.Users
                .Where(u => u.PocketId == userId)
                .FirstOrDefaultAsync();

            var viewModel = new DashboardViewModel
            {
                ActiveServers = await _context.Servers.CountAsync(s => s.IsOnline),
                OfflineServers = await _context.Servers.CountAsync(s => !s.IsOnline),
                RunningContainers = await _context.Containers.CountAsync(c => c.IsRunning),
                FailedContainers = await _context.Containers.CountAsync(c => !c.IsRunning),
                LastLogin = user?.LastLogin ?? DateTime.MinValue
            };

            return View(viewModel);
        }
    }
}
