using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NexusRMM.Core.Models;
using NexusRMM.Infrastructure.Data;

namespace NexusRMM.Api.Controllers;

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

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CreateTaskRequest request)
    {
        var task = new TaskItem
        {
            Id = Guid.NewGuid(),
            AgentId = request.AgentId,
            Type = request.Type,
            Payload = request.Payload is not null ? JsonSerializer.SerializeToElement(request.Payload) : null,
            CreatedAt = DateTime.UtcNow
        };
        _db.Tasks.Add(task);
        await _db.SaveChangesAsync();
        return CreatedAtAction(nameof(GetById), new { id = task.Id }, task);
    }

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

    [HttpGet("agent/{agentId:guid}")]
    public async Task<IActionResult> GetByAgent(Guid agentId)
    {
        var tasks = await _db.Tasks
            .Where(t => t.AgentId == agentId)
            .OrderByDescending(t => t.CreatedAt)
            .Take(50)
            .ToListAsync();
        return Ok(tasks);
    }
}

public record CreateTaskRequest(Guid AgentId, TaskType Type, object? Payload);
