using Microsoft.AspNetCore.Mvc;
using MvcAcessoIP.Models;
using System.Diagnostics;
using System.Net;

namespace MvcAcessoIP.Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    public HttpClient _httpClient;

    public HomeController(ILogger<HomeController> logger, HttpClient httpClient)
    {
        _logger = logger;
        _httpClient = httpClient;
    }

    public IActionResult Index()
    {
        return View();
    }

    public async Task<IActionResult> ConsomeAPI()
    {
        var response = await _httpClient.GetAsync($"api/bloqueioip/desbloqueado");

        if (response.IsSuccessStatusCode)
        {
            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                ViewBag.Resultado = $"Status Code : {response.StatusCode}";
                return View();
            }

            var resultado = await response.Content.ReadAsStringAsync();

            ViewBag.Resultado = resultado;
        }
        else
        {
            var message = await response.Content.ReadAsStringAsync();
            ViewBag.Resultado = $"Status Code : {response.StatusCode} {message}";
            _logger.LogError($" Não foi possivel acessar o endpoint  - {message}");
        }
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}