using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Meezi.API.Models.Public;
using Meezi.API.Services;
using Meezi.Shared;

namespace Meezi.API.Controllers;

[ApiController]
[Route("api/public/coffee-advisor")]
public class PublicCoffeeAdvisorController : ControllerBase
{
    private readonly ICoffeeAdvisorService _advisor;
    private readonly IValidator<CoffeeAdvisorRequest> _validator;

    public PublicCoffeeAdvisorController(
        ICoffeeAdvisorService advisor,
        IValidator<CoffeeAdvisorRequest> validator)
    {
        _advisor = advisor;
        _validator = validator;
    }

    [HttpPost]
    [EnableRateLimiting("public-write")]
    public async Task<IActionResult> Recommend(
        [FromBody] CoffeeAdvisorRequest request,
        CancellationToken cancellationToken)
    {
        var validation = await _validator.ValidateAsync(request, cancellationToken);
        if (!validation.IsValid)
        {
            var first = validation.Errors[0];
            return BadRequest(new ApiResponse<object>(false, null,
                new ApiError("VALIDATION_ERROR", first.ErrorMessage, first.PropertyName)));
        }

        var (data, code, message) = await _advisor.RecommendAsync(request, cancellationToken);
        if (data is null)
        {
            return code switch
            {
                "AI_NOT_CONFIGURED" => StatusCode(503, new ApiResponse<object>(false, null,
                    new ApiError(code, message ?? "Advisor unavailable."))),
                _ => BadRequest(new ApiResponse<object>(false, null,
                    new ApiError(code ?? "AI_FAILED", message ?? "Request failed.")))
            };
        }

        return Ok(new ApiResponse<CoffeeAdvisorResultDto>(true, data));
    }
}
