using Microsoft.AspNetCore.Mvc;
using OnlyOneAccessTemplate.Services;

namespace OnlyOneAccessTemplate.Controllers
{
    [Route("api/menu")]
    public class MenuController : ControllerBase
    {
        private readonly IModuleService _moduleService;

        public MenuController(IModuleService moduleService)
        {
            _moduleService = moduleService;
        }

        [HttpGet("converters")]
        public async Task<IActionResult> GetConvertersMenu(string language = "pt")
        {
            try
            {
                var modules = await _moduleService.GetAllActiveModulesAsync();

                var menuItems = modules
                    .Where(m => m.ShowInMenu && m.IsActive && m.IsHealthy)
                    .OrderBy(m => m.MenuOrder)
                    .ThenBy(m => m.MenuTitle)
                    .GroupBy(m => m.MenuCategory)
                    .Select(g => new
                    {
                        category = g.Key,
                        items = g.Select(m => new
                        {
                            moduleId = m.ModuleId,
                            title = m.SeoTitles.ContainsKey(language) ? m.SeoTitles[language] : m.MenuTitle,
                            description = m.SeoDescriptions.ContainsKey(language) ? m.SeoDescriptions[language] : m.MenuDescription,
                            icon = m.MenuIcon,
                            url = $"/{language}/{m.RequestBy}",
                            order = m.MenuOrder,
                            isNew = m.CreatedAt > DateTime.UtcNow.AddDays(-7) // Novos nos últimos 7 dias
                        }).ToList()
                    }).ToList();

                return Ok(new { success = true, menu = menuItems });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { success = false, message = ex.Message });
            }
        }
    }
}