using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Text.Json;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.Web.Services.Interfaces;

namespace WorkFlowCheck.Web.Pages.Account
{
    [AllowAnonymous]
    public class LoginModel : PageModel
    {

        private readonly IUserService _userService;
        [BindProperty]
        public User2FADTO User2FADTO { get; set; }

        public string ErrorMessage { get; set; }

        public LoginModel(IUserService userService)
        {
            _userService = userService;
        }

        public void OnGet()
        {
        }
        public async Task<IActionResult> OnPostLogin2F1([FromBody] UserSimpleDTO userSimpleDTO)
        {
            var response = await _userService.Authenticate2F1(userSimpleDTO.UserName, userSimpleDTO.Password);

            if (response.IsSuccess)
            {
                return new JsonResult(new { success = true, data = response.Data });
            }
            else
            {
                ErrorMessage = "Hibás bejelentkezés!";
                return new JsonResult(new { success = false });
            }
        }
        public async Task<IActionResult> OnPostLogin2F2([FromBody] User2FADTO user2FADTO)
        {
            var response = await _userService.Authenticate2F2(user2FADTO.UserName,
                                                              user2FADTO.Password,
                                                              user2FADTO.Code,
                                                              user2FADTO.Token2FA);

            if (response.IsSuccess)
            {

                var token = response.Data.JwtToken;

                Response.Cookies.Append("AuthToken", token, new CookieOptions
                {
                    HttpOnly = true,
                    Secure = true,
                    SameSite = SameSiteMode.Strict,
                    Expires = DateTimeOffset.UtcNow.AddDays(1)
                });

                return new JsonResult(new { success = true });
            }

            ErrorMessage = "Hibás bejelentkezés!";
            return new JsonResult(new { success = false });
        }
    }
}
