using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.IdentityModel.Tokens.Jwt;
using System;

namespace OBSBoardsWWW.Controllers
{
    public class AuthController : Controller
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public AuthController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

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

        [HttpPost]
        public async Task<IActionResult> Login(string username, string password)
        {
            var loginModel = new
            {
                Username = username,
                Password = password
            };

            var client = _httpClientFactory.CreateClient();
            var content = new StringContent(JsonConvert.SerializeObject(loginModel), Encoding.UTF8, "application/json");

            // Wysyłamy żądanie logowania do API
            var response = await client.PostAsync("https://localhost:44372/api/Authenticate/Login", content);
            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                var tokenData = JsonConvert.DeserializeObject<TokenModel>(responseContent);

                // Przechowaj token JWT i refresh token w sesji
                HttpContext.Session.SetString("AccessToken", tokenData.Token);
                HttpContext.Session.SetString("RefreshToken", tokenData.RefreshToken);
                var jwtToken = new JwtSecurityTokenHandler().ReadToken(tokenData.Token) as JwtSecurityToken;
                var expiration = jwtToken.ValidTo;
                HttpContext.Session.SetString("TokenExpiration", expiration.ToString());

                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, username),
                    new Claim("jwt", tokenData.Token) // Własny claim z tokenem JWT
                };
                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var principal = new ClaimsPrincipal(identity);

                // Zaloguj użytkownika do aplikacji klienckiej
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);


                return RedirectToAction("Index", "Home");
            }

            ModelState.AddModelError("", "Nieudane logowanie");
            return View();
        }

        [HttpPost]
        public IActionResult Logout()
        {
            // Usuń token JWT z sesji
            HttpContext.Session.Remove("AccessToken");

            // Wyloguj użytkownika z aplikacji klienckiej i wyczyść ClaimsPrincipal
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            // Przekierowanie na stronę logowania lub główną
            return RedirectToAction("Login", "Auth");
        }
    }
    
    public class TokenModel
    {
        public string Token { get; set; }
        public string RefreshToken { get; set; }
    }
}
