using System.ComponentModel.DataAnnotations;
using Asp.Versioning;
using Baya.Infrastructure.CrossCutting.Seams;
using Baya.WebFramework.Attributes;
using Baya.WebFramework.BaseController;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using AppModels = Baya.Application.Models.Common;

namespace Baya.Web.Api.Controllers.V1;

[ApiVersion("1")]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[Display(Description = "Development-only helpers (return 404 outside the Development environment)")]
public sealed class DevController(IHostEnvironment environment) : BaseController
{
    /// <summary>
    /// Development-only: returns the most recent OTP for <paramref name="phone"/> so a browser or an
    /// automated end-to-end flow can complete phone-OTP login without an SMS gateway (the code is otherwise
    /// only written to the server log by <c>LoggingSmsSender</c>). Returns 404 in every non-Development
    /// environment — the capture is not even wired there — so it can never leak a code in staging/production.
    /// It does not touch the OTP rate-limit or the per-phone resend window. Superseded by the real SMS gateway
    /// in refinement Phase 8.
    /// </summary>
    [HttpGet("[action]/{phone}")]
    [ProducesOkApiResponseType<DevLastOtpResult>]
    public IActionResult LastOtp(string phone)
    {
        if (!environment.IsDevelopment())
            return NotFound();

        var code = HttpContext.RequestServices.GetService<DevOtpStore>()?.GetLatest(phone);

        return code is null
            ? OperationResult(AppModels.OperationResult<DevLastOtpResult>.NotFoundResult("No OTP has been issued for this phone yet."))
            : OperationResult(AppModels.OperationResult<DevLastOtpResult>.SuccessResult(new DevLastOtpResult(phone, code)));
    }
}

/// <summary>The most recent OTP captured for a phone (Development only).</summary>
public record DevLastOtpResult(string Phone, string Code);
