using Microsoft.AspNetCore.Mvc;
using CarneiroTech.Resources;
using CarneiroTech.Services;

namespace CarneiroTech.Controllers;

public class CasesController : Controller
{
    private readonly ICaseService _caseService;
    private readonly ILogger<CasesController> _logger;
    private readonly ILanguageService _languageService;

    public CasesController(ICaseService caseService, ILogger<CasesController> logger, ILanguageService languageService)
    {
        _caseService = caseService;
        _logger = logger;
        _languageService = languageService;
    }

    // GET: /cases
    public async Task<IActionResult> Index(string? tag)
    {
        var cases = string.IsNullOrEmpty(tag)
            ? await _caseService.GetAllCasesAsync()
            : await _caseService.GetCasesByTagAsync(tag);

        var allTags = await _caseService.GetAllTagsAsync();
        var lang = _languageService.GetCurrentLanguage(HttpContext);

        ViewData["Title"] = string.IsNullOrEmpty(tag)
            ? SiteStrings.Get("cases.seo.title", lang)
            : string.Format(SiteStrings.Get("cases.seo.title.tag", lang), tag);
        ViewData["Description"] = string.IsNullOrEmpty(tag)
            ? SiteStrings.Get("cases.seo.description", lang)
            : string.Format(SiteStrings.Get("cases.seo.description.tag", lang), tag);
        ViewData["SelectedTag"] = tag;
        ViewBag.AllTags = allTags;

        return View(cases);
    }

    // GET: /cases/{slug}
    [Route("cases/{slug}")]
    public async Task<IActionResult> Details(string slug)
    {
        var caseModel = await _caseService.GetCaseBySlugAsync(slug);

        if (caseModel == null)
        {
            _logger.LogWarning($"Case not found: {slug}");
            return NotFound();
        }

        ViewData["Title"] = !string.IsNullOrEmpty(caseModel.Metadata.SeoTitle)
            ? caseModel.Metadata.SeoTitle
            : caseModel.Metadata.Title;
        ViewData["Description"] = !string.IsNullOrEmpty(caseModel.Metadata.SeoDescription)
            ? caseModel.Metadata.SeoDescription
            : caseModel.Metadata.Summary;
        ViewData["Keywords"] = caseModel.Metadata.SeoKeywords;
        ViewData["OgImage"] = caseModel.Metadata.Image;

        return View(caseModel);
    }
}
