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

namespace OnlyOneAccessTemplate.Controllers
{
    public class ModuleController : Controller
    {
        private readonly IModuleService _moduleService;
        private readonly ILogger<ModuleController> _logger;

        public ModuleController(IModuleService moduleService, ILogger<ModuleController> logger)
        {
            _moduleService = moduleService;
            _logger = logger;
        }

        [HttpGet]
        public async Task<IActionResult> GetModule(string moduleId)
        {
            if (string.IsNullOrEmpty(moduleId))
            {
                return BadRequest("ModuleId é obrigatório");
            }

            try
            {
                var content = await _moduleService.GetModuleContentAsync(moduleId);
                return Content(content, "text/html");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Erro ao carregar módulo {ModuleId}", moduleId);
                return StatusCode(500, "<p>Erro interno do servidor.</p>");
            }
        }

        [HttpPost]
        public async Task<IActionResult> RefreshModule(string moduleId)
        {
            // Para forçar refresh do cache quando necessário
            var content = await _moduleService.GetModuleContentAsync(moduleId);
            return Json(new { success = true, content });
        }
    }
}
