using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nexus.Api.Models;
using Nexus.Api.Repositories;

namespace Nexus.Api.Controllers;

[Authorize]
[ApiController]
[Route("api/v1/activity")]
public sealed class ActivityController(IActivityRepository activityRepo) : ControllerBase
{
    [HttpGet]
    [ProducesResponseType(typeof(ActivityPageDto), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status401Unauthorized)]
    public async Task<ActionResult<ActivityPageDto>> Get(
        [FromQuery] string? type,
        [FromQuery] string? sort,
        [FromQuery] int? page,
        [FromQuery] int? pageSize,
        CancellationToken ct)
    {
        var take = Math.Clamp(pageSize ?? 20, 1, 200);
        var pageNum = Math.Max(page ?? 1, 1);

        var (items, totalCount) = await activityRepo.GetPagedAsync(type, sort, pageNum, take, ct);

        return Ok(new ActivityPageDto(
            items.Select(item => new ActivityItemDto(
                item.Id,
                item.Type,
                item.Message,
                item.CreatedAt,
                item.TaskId is Guid taskId
                    ? new EntityRefDto("task", taskId.ToString(), null)
                    : null)).ToArray(),
            totalCount,
            pageNum,
            take,
            (int)Math.Ceiling((double)totalCount / take)));
    }
}
