using GestionaDenuncias.Shared.Models;
using ApiDenuncias.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ApiDenuncias.Controllers;

[ApiController]
[Authorize]
[Route("api/tracking")]
public sealed class TrackingController : ControllerBase
{
    private readonly IInboxTrackingService _trackingService;

    public TrackingController(IInboxTrackingService trackingService)
    {
        _trackingService = trackingService;
    }

    [HttpGet("user-state")]
    public Task<InboxUserState> GetUserState(CancellationToken cancellationToken)
        => _trackingService.GetUserStateAsync(GetUsername(), cancellationToken);

    [HttpPost("snapshot")]
    public Task<IReadOnlyList<ReportDto>> RegisterSnapshot(
        TrackingSnapshotRequest request,
        CancellationToken cancellationToken)
        => _trackingService.RegisterSnapshotAsync(GetUsername(), request.Reports, cancellationToken);

    [HttpPost("imported")]
    public async Task<IActionResult> MarkImported(MarkReportImportedRequest request, CancellationToken cancellationToken)
    {
        await _trackingService.MarkReportImportedAsync(GetUsername(), request.Report, request.ComplaintId, cancellationToken);
        return Ok(new { ok = true });
    }

    [HttpPost("handled-in-gestiona")]
    public async Task<IActionResult> MarkHandledInGestiona(
        MarkReportHandledInGestionaRequest request,
        CancellationToken cancellationToken)
    {
        await _trackingService.MarkReportHandledInGestionaAsync(
            GetUsername(),
            request.DenunciaId,
            request.UploadedAtUtc,
            cancellationToken);
        return Ok(new { ok = true });
    }

    [HttpPost("import-permission")]
    public async Task<IActionResult> EnsureImportPermission(
        TrackingImportPermissionRequest request,
        CancellationToken cancellationToken)
    {
        await _trackingService.EnsureReportCanBeImportedByUserAsync(GetUsername(), request.Report, cancellationToken);
        return Ok(new { ok = true });
    }

    private string GetUsername()
        => User.Identity?.Name ?? throw new InvalidOperationException("No hay usuario autenticado.");
}
