using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NexusRMM.Infrastructure.Data;

namespace NexusRMM.Api.Controllers;

[ApiController]
[Route("api/v1/[controller]")]
public class AgentsController : ControllerBase
{
    private readonly RmmDbContext _db;
    public AgentsController(RmmDbContext db) => _db = db;

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var agents = await _db.Agents
            .OrderBy(a => a.Hostname)
            .Select(a => new { a.Id, a.Hostname, a.OsType, a.OsVersion, a.IpAddress, a.Status, a.AgentVersion, a.LastSeen, a.Tags })
            .ToListAsync();
        return Ok(agents);
    }

    [HttpGet("{id:guid}")]
    public async Task<IActionResult> GetById(Guid id)
    {
        var agent = await _db.Agents.FindAsync(id);
        return agent is null ? NotFound() : Ok(agent);
    }

    [HttpGet("{id:guid}/metrics")]
    public async Task<IActionResult> GetMetrics(Guid id, [FromQuery] int hours = 24)
    {
        var since = DateTime.UtcNow.AddHours(-hours);
        var metrics = await _db.AgentMetrics
            .Where(m => m.AgentId == id && m.Timestamp >= since)
            .OrderByDescending(m => m.Timestamp)
            .Take(1000)
            .Select(m => new { m.Timestamp, m.Metrics })
            .ToListAsync();
        return Ok(metrics);
    }
}
