using Microsoft.AspNetCore.Mvc;
using SIGCM2.Api.Authorization;
using SIGCM2.Application.Audit;

namespace SIGCM2.Api.Controllers;

/// <summary>
/// UDT-010: Read-only endpoint for audit events. Requires administracion:auditoria:ver.
/// Cursor-based DESC pagination with 4 filter axes (actor/target/from/to).
/// Rich UI (drilldown, export CSV, timeline) is deferred to ADM-004.
/// </summary>
[ApiController]
[Route("api/v1/audit")]
public sealed class AuditController : ControllerBase
{
    private readonly IAuditEventRepository _repo;

    public AuditController(IAuditEventRepository repo)
    {
        _repo = repo;
    }

    /// <summary>Lists audit events with optional filters. Cursor-based DESC pagination.</summary>
    [HttpGet("events")]
    [RequirePermission("administracion:auditoria:ver")]
    [ProducesResponseType(typeof(AuditEventPageResponse), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status401Unauthorized)]
    [ProducesResponseType(StatusCodes.Status403Forbidden)]
    public async Task<IActionResult> GetEvents(
        [FromQuery] int? actorUserId = null,
        [FromQuery] string? targetType = null,
        [FromQuery] string? targetId = null,
        [FromQuery] DateTime? from = null,
        [FromQuery] DateTime? to = null,
        [FromQuery] string? cursor = null,
        [FromQuery] int limit = 50,
        CancellationToken ct = default)
    {
        if (limit < 1 || limit > 100)
            return BadRequest(new { error = "limit must be between 1 and 100" });

        if (from is not null && to is not null && from > to)
            return BadRequest(new { error = "from must be <= to" });

        var filter = new AuditEventFilter(
            ActorUserId: actorUserId,
            TargetType: targetType,
            TargetId: targetId,
            From: from,
            To: to,
            Cursor: cursor,
            Limit: limit);

        var result = await _repo.QueryAsync(filter, ct);
        return Ok(new AuditEventPageResponse(result.Items, result.NextCursor));
    }
}

/// <summary>UDT-010: Paginated response wrapper for GET /api/v1/audit/events.</summary>
public sealed record AuditEventPageResponse(
    IReadOnlyList<AuditEventDto> Items,
    string? NextCursor);
