using System.ComponentModel.DataAnnotations;
using Asp.Versioning;
using Baya.Application.Features.Identity.Commands.Logout;
using Baya.Application.Features.Identity.Commands.RefreshToken;
using Baya.Application.Features.Identity.Commands.RequestOtp;
using Baya.Application.Features.Identity.Commands.VerifyOtp;
using Baya.Application.Models.Identity;
using Baya.WebFramework.Attributes;
using Baya.WebFramework.BaseController;
using Baya.WebFramework.ServiceConfiguration;
using Baya.WebFramework.Swagger;
using Mediator;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;

namespace Baya.Web.Api.Controllers.V1;

[ApiVersion("1")]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[Display(Description = "Phone-OTP login, refresh-token rotation and logout")]
public sealed class AuthController(ISender sender) : BaseController
{
    [HttpPost("[action]")]
    [EnableRateLimiting(RateLimitingServiceExtension.OtpPolicy)]
    [ProducesOkApiResponseType<RequestOtpResult>]
    public async Task<IActionResult> RequestOtp(RequestOtpCommand command, CancellationToken cancellationToken)
        => OperationResult(await sender.Send(command, cancellationToken));

    [HttpPost("[action]")]
    [EnableRateLimiting(RateLimitingServiceExtension.OtpPolicy)]
    [ProducesOkApiResponseType<AuthTokensResult>]
    public async Task<IActionResult> VerifyOtp(VerifyOtpCommand command, CancellationToken cancellationToken)
        => OperationResult(await sender.Send(command, cancellationToken));

    // Runs without a valid access token — the refresh token itself is the credential.
    [HttpPost("[action]")]
    [EnableRateLimiting(RateLimitingServiceExtension.AuthPolicy)]
    [RequireTokenWithoutAuthorization]
    [ProducesOkApiResponseType<AuthTokensResult>]
    public async Task<IActionResult> Refresh(RefreshTokenCommand command, CancellationToken cancellationToken)
        => OperationResult(await sender.Send(command, cancellationToken));

    [HttpPost("[action]")]
    [Authorize]
    [ProducesOkApiResponseType]
    public async Task<IActionResult> Logout(LogoutCommand command, CancellationToken cancellationToken)
        => OperationResult(await sender.Send(command, cancellationToken));
}