using System.ComponentModel.DataAnnotations;
using EnotaryoPH.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

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

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

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

        public async Task<IActionResult> OnGetLogoutAsync()
        {
            await _signInService.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();
            }

            await _signInService.SignInAsync(new UserLogin
            {
                Email = user.Email,
                Role = user.Role,
                User_UID = user.User_UID.Value
            });

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

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

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