using Microsoft.AspNetCore.Mvc;
using PlotLine.Services;
using PlotLine.ViewModels;

namespace PlotLine.Controllers;

[Route("Help")]
public sealed class HelpController(IHelpService help, IHelpMarkdownRenderer markdown) : Controller
{
    [HttpGet("")]
    public IActionResult Index(string? q)
    {
        var articles = help.GetAllArticles();
        return View(new HelpCentreIndexViewModel
        {
            Query = q,
            ArticleCount = articles.Count,
            Categories = help.GetCategories()
                .Select(category => new HelpCategoryViewModel
                {
                    CategoryName = category,
                    ArticleCount = help.GetByCategory(category).Count
                })
                .ToList(),
            SearchResults = string.IsNullOrWhiteSpace(q) ? [] : help.Search(q),
            RecentArticles = articles.OrderByDescending(x => x.RelativePath).Take(5).ToList()
        });
    }

    [HttpGet("Category/{category}")]
    public IActionResult Category(string category)
    {
        var articles = help.GetByCategory(category);
        return View(new HelpCategoryArticlesViewModel
        {
            CategoryName = category,
            Articles = articles
        });
    }

    [HttpGet("Article/{key}")]
    public IActionResult Article(string key)
    {
        var article = help.GetByContextKey(key);
        if (article is null)
        {
            return View("ArticleNotFound", key);
        }

        return View(new HelpCentreArticleViewModel
        {
            Article = article,
            RenderedHtml = markdown.Render(article.MarkdownContent),
            RelatedArticles = help.GetRelatedArticles(article)
        });
    }
}
