using System.Security.Claims;
using LaneFlowReport.Auth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;

namespace LaneFlowReport.Controllers {
    public class LoginController: Controller {
        private readonly ParkingAuthProvider _parkingAuthProvider;
        public LoginController(ParkingAuthProvider parkingAuthProvider) {
            _parkingAuthProvider = parkingAuthProvider;
        }

        [HttpGet]
        public async Task<IActionResult> LoginCallback(string mode, string providerKey) {
            var accessCode = $"{mode};{providerKey}";
            var result = await _parkingAuthProvider.GetUserInfo(accessCode);
            var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new[] {
                new Claim(ClaimTypes.Name, result.UserName),
                new Claim(ClaimTypes.Role, "Report"),
            }, "Cookies"));

            var authProperties = new AuthenticationProperties {
                IsPersistent = true
            };
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsPrincipal), authProperties);
            HttpContext.User = claimsPrincipal;
            ViewBag.Status = "authing...";
            ViewBag.RedirectUrl = Url.Action("Index", "Report", null, HttpContext.Request.Scheme);
            return View();
        }
    }
}
