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 UserDTO UserSimpleDTO { get; set; }
        public string ErrorMessage { get; set; }

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

        public void OnGet()
        {
        }
        public async Task<IActionResult> OnPostAsync()
        {
            var response = await _userService.Authenticate(UserSimpleDTO.UserName, UserSimpleDTO.Password);

            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.AddMinutes(30)
                });

                return RedirectToPage("/Index"); // vagy ahová szeretnéd
            }

            ErrorMessage = "Hibás bejelentkezés!";
            return Page();
        }
    }
}
