using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using CouponReport.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.Text.Json;
using System.Text;
using LaneFlowReport.Options;
using LaneFlowReport.Models;

namespace CouponReport.Controllers;

public class HomeController : Controller
{
	private readonly ILogger<HomeController> _logger;
	private readonly IHttpClientFactory _httpClientFactory;
	private readonly IOptions<OauthOption> _oauthOption;

	public HomeController(ILogger<HomeController> logger, IHttpClientFactory httpClientFactory, IOptions<OauthOption> oauthOption)
	{
		_logger = logger;
		_httpClientFactory = httpClientFactory;
		_oauthOption = oauthOption;
	}
	public IActionResult Index()
	{
		//如果已經登入，直接導向報表頁面
		if (User.Identity?.IsAuthenticated == true)
		{
			return RedirectToAction("Index", "Report");
		}

		ViewBag.OauthUrl = _oauthOption.Value.ParkingOAuthUrl;
		return View(new LoginViewModel());
	}


	[HttpPost]
	public async Task<IActionResult> Index(LoginViewModel model)
	{
		ViewBag.OauthUrl = _oauthOption.Value.ParkingOAuthUrl;
		if (ModelState.IsValid)
		{
			if (await ValidateCredentialsAsync(model))
			{
				var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new[]
				{
					new Claim(ClaimTypes.Name, model.Username),
					new Claim(ClaimTypes.Role, "Report"),
				}, "Cookies"));

				var authProperties = new AuthenticationProperties
				{
					IsPersistent = false
				};
				await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
					new ClaimsPrincipal(claimsPrincipal), authProperties);

				return RedirectToAction("Index", "Report", new { });
			}
			else
			{
				ModelState.AddModelError(string.Empty, "登入失敗！");
				model.Password = "";
			}

		}
		return View(model);
	}

	//驗證帳號
	private async Task<bool> ValidateCredentialsAsync(LoginViewModel model)
	{
		var client = _httpClientFactory.CreateClient();
		var endPoint = _oauthOption.Value.ParkingLoginUrl;
		var data = new
		{
			userNameOrEmailAddress = model.Username,
			password = model.Password,
			tenancyName = "Altob"
		};

		var json = JsonSerializer.Serialize(data);
		var content = new StringContent(json, Encoding.UTF8, "application/json");

		try
		{
			var response = await client.PostAsync(endPoint, content);
			var responseString = await response.Content.ReadAsStringAsync();

			_logger.LogInformation($"API Response: {responseString}");

			if (response.IsSuccessStatusCode)
			{
				//var result = JsonSerializer.Deserialize<AuthenticationResult>(responseString);
				//if (result != null && result.StatusCode == 200 && result.Msg == "成功")
				//{
					return true;
				//}
			}
			else
			{
				return false;
			}
		}
		catch (Exception ex)
		{
			_logger.LogError(ex, "驗證有誤");
		}
		return false;
	}

	//登出
	[HttpPost]
	[ValidateAntiForgeryToken]
	public async Task<IActionResult> Logout()
	{
		await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
		HttpContext.Session.Clear();

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

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


	public class AuthenticationResult
	{
		public string Msg { get; set; }
		public int StatusCode { get; set; }
	}
}
