using Microsoft.AspNetCore.Mvc;
using QRRapidoApp.Services;

namespace QRRapidoApp.Controllers
{
    public class DevTutoriaisController : Controller
    {
        private readonly IMarkdownService _markdownService;
        private readonly ILogger<DevTutoriaisController> _logger;
        private const string ContentFolder = "DevTutoriais";

        public DevTutoriaisController(IMarkdownService markdownService, ILogger<DevTutoriaisController> logger)
        {
            _markdownService = markdownService;
            _logger = logger;
        }

        [Route("Developer/docs")]
        [Route("es/Developer/docs")]
        [Route("en/Developer/docs")]
        public async Task<IActionResult> Index()
        {
            var culture = GetCulture();
            var articles = await _markdownService.GetAllArticlesAsync(culture, ContentFolder);
            ViewBag.Culture = culture;
            return View(articles);
        }

        [Route("Developer/docs/{slug}")]
        [Route("es/Developer/docs/{slug}")]
        [Route("en/Developer/docs/{slug}")]
        public async Task<IActionResult> Article(string slug)
        {
            var culture = GetCulture();
            var article = await _markdownService.GetArticleAsync(slug, culture, ContentFolder);

            if (article == null)
            {
                _logger.LogWarning("Dev article not found: {Slug} ({Culture})", slug, culture);
                return NotFound();
            }

            var allArticles = await _markdownService.GetAllArticlesAsync(culture, ContentFolder);
            article.RelatedArticles = allArticles
                .Where(a => a.Slug != slug)
                .Take(3)
                .ToList();

            ViewBag.Culture = culture;
            ViewBag.Slug = slug;
            return View(article);
        }

        private string GetCulture()
        {
            var path = Request.Path.Value ?? "";
            if (path.StartsWith("/es/", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(path, "/es", StringComparison.OrdinalIgnoreCase)) return "es";
            if (path.StartsWith("/en/", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(path, "/en", StringComparison.OrdinalIgnoreCase)) return "en";
            return "pt-BR";
        }
    }
}
