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

[Authorize]
public class ServerController : Controller
{
    private readonly AppDbContext _context;

    private readonly ILogger<ServerController> _logger;

    public ServerController(AppDbContext context, ILogger<ServerController> logger)
    {
        _context = context;
        _logger = logger;
    }

    public async Task<IActionResult> Overview()
    {
        var vm = new ServerOverviewViewModel
        {
            Servers = await _context.Servers.OrderBy(s => s.Id).ToListAsync()
        };

        return View(vm);
    }

    [HttpGet]
    public IActionResult AddServer()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> AddServer(AddServerViewModel vm)
    {
        if (!ModelState.IsValid)
            return View(vm);

        var server = new Server
        {
            Name = vm.Name,
            IPAddress = vm.IPAddress,
            Type = vm.Type,
            IsOnline = vm.IsOnline,
        };

        _context.Servers.Add(server);
        await _context.SaveChangesAsync();

        _logger.LogInformation("Neuer Server erstellt: {server}", server.Name);

        return RedirectToAction(nameof(Overview));
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Delete(int id)
    {
        var server = await _context.Servers.FindAsync(id);
        if (server == null)
        {
            _logger.LogError("Server nicht gefunden");
            return NotFound();
        }

        _context.Servers.Remove(server);
        await _context.SaveChangesAsync();

        _logger.LogInformation("Server '{server}' erfolgreich gelöscht", server.Name);

        return RedirectToAction(nameof(Overview));
    }

    // GET: Server/Edit/5
    public async Task<IActionResult> EditServer(int id)
    {
        var server = await _context.Servers.FindAsync(id);
        if (server == null) return NotFound();

        var vm = new EditServerViewModel
        {
            Name = server.Name,
            IPAddress = server.IPAddress,
            Type = server.Type
        };

        return View(vm);
    }

    // POST: Server/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> EditServer(int id, EditServerViewModel vm)
    {
        if (!ModelState.IsValid)
        {
            return View(vm);
        }

        var server = await _context.Servers.FindAsync(id);
        if (server == null)
        {
            return NotFound();
        }

        server.Name = vm.Name;
        server.IPAddress = vm.IPAddress;
        server.Type = vm.Type;

        try
        {
            await _context.SaveChangesAsync();
            _logger.LogInformation("Server '{server}' erfolgreich aktualisiert", server.Name);
            return RedirectToAction(nameof(Overview));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Fehler beim Speichern des Servers");
            ModelState.AddModelError("", "Fehler beim Speichern");
            return View(vm);
        }
    }

    // GET: Server/Details/5
    [HttpGet]
    public async Task<IActionResult> Details(int id)
    {

        var s = await _context.Servers.FindAsync(id);
        if (s == null) return NotFound();

        var vm = new ServerDetailsViewModel
        {
            Id = s.Id,
            Name = s.Name,
            IPAddress = s.IPAddress,
            Type = s.Type,
            Description = s.Description,
            CpuType = s.CpuType,
            CpuCores = s.CpuCores,
            GpuType = s.GpuType,
            RamSize = s.RamSize,
            CreatedAt = s.CreatedAt,
            IsOnline = s.IsOnline,
            LastSeen = s.LastSeen,
            IsVerified = s.IsVerified
        };

        return View(vm);
    }

    public async Task<IActionResult> ServerCardsPartial()
    {
        var servers = _context.Servers.ToList();

        foreach (var server in servers)
        {
            server.IsOnline = (DateTime.UtcNow - server.LastSeen).TotalSeconds <= 120;
            await _context.SaveChangesAsync();
        }

        return PartialView("_ServerCard", servers);
    }


}
