using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace OlympiaIntranet
{
    public partial class Verify2FA : System.Web.UI.Page
    {
        private static readonly TimeSpan TwoFATimeout = TimeSpan.FromHours(4);
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                //string username = Session["2FA_UserId"].ToString();
                //MembershipUser user = Membership.GetUser(username);
                //string email = user?.Email;
                string userId = Session["2FA_UserId"]?.ToString();
                if (!string.IsNullOrEmpty(userId))
                {
                    var userStore = new UserStore<IdentityUser>();
                    var userManager = new UserManager<IdentityUser>(userStore);

                    var user = userManager.FindById(userId);

                    if (user != null)
                    {
                        string email = user.Email;       // <-- qui ottieni l'email
                        if (!string.IsNullOrEmpty(email))
                        {
                            string maskedEmail = MaskEmail(email);
                            litInfoEmail.Text = $"<p>Inserisci il codice che ti abbiamo inviato all'email <strong>{maskedEmail}</strong></p>";
                        }
                        else
                        {
                            litInfoEmail.Text = "<p>Inserisci il codice che ti abbiamo inviato via email</p>";
                        }
                    }
                }


            }
        }
        private string MaskEmail(string email)
        {
            int atIndex = email.IndexOf('@');
            if (atIndex <= 0 || atIndex >= email.Length - 1)
                return email;

            string localPart = email.Substring(0, atIndex);
            string domainPart = email.Substring(atIndex + 1); // rimuove @

            string maskedLocal = localPart.Length <= 5 ? localPart : localPart.Substring(0, 5) + "...";

            // Esempio: da "gmail.com" → "gma..."
            string domainFirstPart = domainPart.Split('.')[0];
            string maskedDomain = domainFirstPart.Length <= 3 ? domainFirstPart : domainFirstPart.Substring(0, 3) + "...";

            return maskedLocal + "@" + maskedDomain;
        }

        protected void btnVerify_Click(object sender, EventArgs e)
        {
            var expectedCode = Session["2FA_Code"]?.ToString();
            var userId = Session["2FA_UserId"]?.ToString();

            //System.Diagnostics.Debug.WriteLine("READ SessionID: " + Session.SessionID);

            if (txtCode.Text == expectedCode && !string.IsNullOrEmpty(userId))
            {
                var userStore = new UserStore<IdentityUser>();
                var userManager = new UserManager<IdentityUser>(userStore);
                var user = userManager.FindById(userId);

                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);

                // Autenticazione
                FormsAuthentication.SetAuthCookie(user.UserName, false);

                // Imposta cookie per durata validità 2FA
                HttpCookie cookie = new HttpCookie("Last2FA");
                cookie.Values["User"] = user.UserName;
                cookie.Values["VerifiedAt"] = DateTime.UtcNow.ToString("o"); // formato ISO
                cookie.HttpOnly = true;
                cookie.Expires = DateTime.UtcNow.Add(TwoFATimeout);
                Response.Cookies.Add(cookie);

                // Pulizia
                Session["2FA_Code"] = null;
                Session["2FA_UserId"] = null;

                if (user.UserName == "external")
                    Response.Redirect("~/EsposizioneCertificati.aspx");
                else
                    Response.Redirect("~/Default2.aspx");
            }
            else
            {
                lblMessage.Visible = true;
                lblMessage.CssClass = "alert alert-danger";
                lblMessage.Text = "Codice non valido!";
            }
        }
    }
}