using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis;
using Microsoft.EntityFrameworkCore;
using Watcher.Data;
using Watcher.Models;

// eingehender Heartbeat-Payload
public class HeartbeatDto
{
    public string? IpAddress { get; set; }
}

[ApiController]
[Route("[controller]")]
public class HeartbeatController : Controller
{

    // Datenbankverbindung
    private readonly AppDbContext _context;

    // Logging einbinden
    private readonly ILogger<HeartbeatController> _logger;

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

    // Endpoint um Heartbeat-Payloads zu empfangen
    [HttpPost("receive")]
    public async Task<IActionResult> Receive([FromBody] HeartbeatDto dto)
    {
        _logger.LogInformation("Heartbeat empfangen");

        if (string.IsNullOrWhiteSpace(dto.IpAddress))
        {
            _logger.LogWarning("Eingehender Payload enthält keine IP-Adresse");
            return BadRequest("Missing IP address.");
        }

        var server = await _context.Servers
            .FirstOrDefaultAsync(s => s.IPAddress == dto.IpAddress);

        if (server != null)
        {
            server.LastSeen = DateTime.UtcNow;
            await _context.SaveChangesAsync();
            _logger.LogInformation("Heartbeat von {server} in Datenbank eingetragen.", server.Name);
            return Ok();
        }

        _logger.LogWarning("Eingehender Payload kann keiner bekannten IP-Adresse zugewiesen werden.");
        return NotFound("No matching server found.");
    }
}
