using Contracts.BindingModels;
using Contracts.Converters;
using Contracts.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using WebApp.Helpers;

namespace WebApp.Pages.User
{
    [Authorize(Roles = Roles.User)]
    public class SettingsModel : PageModel
    {
        [BindProperty]
        public UserBindingModel UserModel { get; set; }

        public void OnGet()
        {
            var id = this.GetUserId();
            if (id is null)
            {
                return;
            }

            var userView = APIClient.GetRequest<UserViewModel>($"user/get?id={id}");
            if (userView is null)
            {
                throw new Exception("User is not found.");
            }

            UserModel = UserConverter.ToBinding(userView);
        }

        public IActionResult OnPostDeleteProfile()
        {
            var id = this.GetUserId();
            if (id is null)
            {
                throw new Exception("User not found!");
            }

            var response = APIClient.DeleteRequest($"user/delete?id={id}");
            if (response is null)
            {
                throw new Exception("Something wrong LOL!");
            }

            this.DeleteJWT();

            return RedirectToPage("../Index");
        }

        public IActionResult OnPostAsync()
        {
            var response = APIClient.PatchRequest("user/update", UserModel);

            if (response is null)
            {
                throw new Exception("Something wrong LOL!");
            }

            return RedirectToPage("Index");
        }
    }
}