using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using EnotaryoPH.Data;
using EnotaryoPH.Web.Common.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace EnotaryoPH.Web.Pages
{
    public class LoginModel : PageModel
    {
        private readonly NotaryoDBContext _notaryoDBContext;
        private readonly IPasswordService _passwordService;

        public LoginModel(IPasswordService passwordService, NotaryoDBContext notaryoDBContext)
        {
            _passwordService = passwordService;
            _notaryoDBContext = notaryoDBContext;
        }

        public async Task<IActionResult> OnGetAsync() => Page();

        public async Task<IActionResult> OnGetLogoutAsync()
        {
            await HttpContext.SignOutAsync();
            return RedirectToPage("/Login");
        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            var user = _notaryoDBContext.Users.FirstOrDefault(u => EF.Functions.Like(u.Email, Email));
            if (user == null)
            {
                ModelState.AddModelError("", "Invalid Email or Password");
                return Page();
            }

            if (!_passwordService.VerifyHashedPassword(user.PasswordHash, Password))
            {
                ModelState.AddModelError("", "Invalid Email or Password");
                return Page();
            }

            var claims = new List<Claim>
                {
                    new(ClaimTypes.NameIdentifier, user.User_UID.ToString()),
                    new(ClaimTypes.Name, user.Email),
                    new(ClaimTypes.Email, user.Email),
                    new(ClaimTypes.Role, user.Role!)
                };
            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var authProperties = new AuthenticationProperties();

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);

            var returnUrl = Request.Query["ReturnUrl"].ToString() ?? string.Empty;
            return RedirectToPage(string.IsNullOrEmpty(returnUrl) ? "/Principal/Dashboard/Dashboard" : returnUrl);
        }

        [Required]
        [EmailAddress]
        [BindProperty]
        public string Email { get; set; }

        [Required]
        [BindProperty]
        public string Password { get; set; }
    }
}