using Microsoft.AspNetCore.Mvc;
using SentenceConverterModule.Models;
using SentenceConverterModule.Services.Contracts;

namespace SentenceConverterModule.Controllers
{
    [Route("api/converter")]
    public class ConverterController : Controller
    {
        private readonly ISentenceConverterService _converterService;
        private readonly ILogger<ConverterController> _logger;

        public ConverterController(
            ISentenceConverterService converterService,
            ILogger<ConverterController> logger)
        {
            _converterService = converterService;
            _logger = logger;
        }

        [HttpPost("convert")]
        public async Task<IActionResult> Convert([FromForm] ConversionRequestDto requestDto)
        {
            try
            {
                var request = new ConversionRequest(
                    Language: requestDto.Language ?? "pt",
                    InputType: requestDto.InputType,
                    TextInput: requestDto.TextInput,
                    Options: requestDto.Options
                );

                if (!await _converterService.ValidateInputAsync(request))
                {
                    return BadRequest(new { success = false, message = "Entrada inválida" });
                }

                var result = await _converterService.ConvertAsync(request);

                if (!result.Success)
                {
                    return BadRequest(new { success = false, message = result.ErrorMessage });
                }

                return Ok(new
                {
                    success = true,
                    outputText = result.OutputText,
                    metadata = result.Metadata
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Erro na conversão");
                return StatusCode(500, new { success = false, message = "Erro interno do servidor" });
            }
        }

        [HttpGet("config")]
        public IActionResult GetConfig([FromQuery] string language = "pt")
        {
            try
            {
                var config = _converterService.GetConfiguration(language);
                return Ok(new { success = true, config });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Erro ao buscar configuração");
                return StatusCode(500, new { success = false, message = "Erro interno" });
            }
        }

        [HttpGet("widget")]
        public async Task<IActionResult> GetWidget([FromQuery] string language = "pt")
        {
            try
            {
                var config = _converterService.GetConfiguration(language);
                ViewBag.Config = config;
                ViewBag.Language = language;

                return PartialView("_ConverterWidget");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Erro ao gerar widget");
                return StatusCode(500, "Erro ao carregar widget");
            }
        }

        [HttpGet("health")]
        public IActionResult Health()
        {
            return Ok(new
            {
                status = "healthy",
                service = "sentence-converter",
                timestamp = DateTime.UtcNow
            });
        }
    }
}

