using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Postall.Domain.Services.Contracts;
using Postall.Infra.Services;

namespace Postall.Controllers
{
    [Authorize]
    public class ChannelsController : Controller
    {
        private readonly IChannelService _channelService;

        public ChannelsController(IChannelService channelService)
        {
            _channelService = channelService;
        }

        public async Task<IActionResult> Index()
        {
            var userChannels = await _channelService.GetUserChannelsAsync();
            return View(userChannels.IsSuccess ? userChannels.Value : new List<string>());
        }

        [HttpGet]
        public IActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Add(string channelId)
        {
            if (string.IsNullOrEmpty(channelId))
            {
                TempData["Error"] = "ID do canal é obrigatório";
                return RedirectToAction("Add");
            }

            try
            {
                var success = await _channelService.AddChannelAsync(channelId);

                if (success.IsSuccess)
                {
                    TempData["Message"] = "Canal adicionado com sucesso!";
                    return RedirectToAction("Index");
                }

                TempData["Error"] = "Não foi possível adicionar o canal. Ele já existe ou é inválido.";
                return RedirectToAction("Add");
            }
            catch (Exception ex)
            {
                TempData["Error"] = $"Erro ao adicionar canal: {ex.Message}";
                return RedirectToAction("Add");
            }
        }

        [HttpPost]
        public async Task<IActionResult> Remove(string id)
        {
            try
            {
                var success = await _channelService.RemoveChannel(id);

                if (success.IsSuccess)
                    TempData["Message"] = "Canal removido com sucesso!";
                else
                    TempData["Error"] = "Não foi possível remover o canal.";
            }
            catch (Exception ex)
            {
                TempData["Error"] = $"Erro ao remover canal: {ex.Message}";
            }

            return RedirectToAction("Index");
        }

        [HttpGet]
        public async Task<IActionResult> Search(string query)
        {
            if (string.IsNullOrEmpty(query) || query.Length < 3)
            {
                return Json(new { success = false, message = "A consulta deve ter pelo menos 3 caracteres" });
            }

            try
            {
                var results = await _channelService.SearchChannelsAsync(query);
                if (results.IsSuccess)
                    return Json(new { success = true, data = results.Value });

                return Json(new { success = false, message = "Erro ao buscar canais" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
    }
}
