using System.ComponentModel.DataAnnotations;
using Asp.Versioning;
using Baya.Application.Features.Bookings.Commands.CancelSession;
using Baya.Application.Features.Bookings.Commands.CheckInVisit;
using Baya.Application.Features.Bookings.Commands.CheckOutVisit;
using Baya.Application.Features.Bookings.Queries.GetVisitVerification;
using Baya.Application.Features.Bookings.Queries.ListSessionsForNurse;
using Baya.Application.Models.Booking;
using Baya.Application.Models.Common;
using Baya.WebFramework.Attributes;
using Baya.WebFramework.BaseController;
using Baya.WebFramework.ServiceConfiguration;
using Mediator;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;

namespace Baya.Web.Api.Controllers.V1;

/// <summary>
/// The per-visit surface: the assigned nurse's EVV check-in/out, their "today" session list, per-session EVV
/// detail (raw GPS gated to the owning nurse + admin), and a single-session cancel. Tenancy is enforced in
/// the handlers via <c>ICurrentUser</c>.
/// </summary>
[ApiVersion("1")]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[Display(Description = "Booking sessions & EVV (check-in/out, today's visits, EVV detail, session cancel)")]
public sealed class BookingSessionsController(ISender sender) : BaseController
{
    [HttpPost("[action]/{id}")]
    [ProducesOkApiResponseType<VisitVerificationDto>]
    public async Task<IActionResult> CheckIn(long id, CheckInVisitCommand command, CancellationToken cancellationToken)
        => OperationResult(await sender.Send(command with { SessionId = id }, cancellationToken));

    [HttpPost("[action]/{id}")]
    [ProducesOkApiResponseType<VisitVerificationDto>]
    public async Task<IActionResult> CheckOut(long id, CheckOutVisitCommand command, CancellationToken cancellationToken)
        => OperationResult(await sender.Send(command with { SessionId = id }, cancellationToken));

    [HttpGet("[action]")]
    [ProducesOkApiResponseType<PagedResult<BookingSessionListItemDto>>]
    public async Task<IActionResult> Today([FromQuery] ListSessionsForNurseQuery query, CancellationToken cancellationToken)
        => OperationResult(await sender.Send(query, cancellationToken));

    [HttpGet("[action]/{id}")]
    [ProducesOkApiResponseType<VisitVerificationDto>]
    public async Task<IActionResult> Evv(long id, CancellationToken cancellationToken)
        => OperationResult(await sender.Send(new GetVisitVerificationQuery(id), cancellationToken));

    [HttpPost("[action]/{id}")]
    [EnableRateLimiting(RateLimitingServiceExtension.SensitivePolicy)]
    [ProducesOkApiResponseType<CancellationResultDto>]
    public async Task<IActionResult> Cancel(long id, CancelSessionCommand command, CancellationToken cancellationToken)
        => OperationResult(await sender.Send(command with { SessionId = id }, cancellationToken));
}
