using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.VisualBasic;
using SpotifyAPI.Web;

namespace sotd.Pages;

public class UnclaimedPhoneNumbersModel : PageModel
{
    private readonly ILogger<UserModel> _logger;

    public UnclaimedPhoneNumbersModel(ILogger<UserModel> logger)
    {
        _logger = logger;
        UnclaimedUsers = new List<User>();
    }

    public int userId { get; set; }

    [BindProperty]
    public List<User> UnclaimedUsers { get; set; }

    public void OnGet()
    {
        using (var dci = DataContext.Instance)
        {
            this.UnclaimedUsers = dci.Users == null ? new List<User>() : dci.Users.Where(u => string.IsNullOrEmpty(u.LdapUserName)).ToList();
        }
    }

    public void OnPost(int userIndex)
    {
        using (var dci = DataContext.Instance)
        {
            var user = dci.Users.Find(userIndex);
            var claimCodeService = HttpContext.RequestServices.GetService<PhoneClaimCodeProviderService>();
            claimCodeService.GenerateClaimCodeForUserAndNumber(HttpContext.User.Identity.Name, user.SignalMemberId);
            this.UnclaimedUsers = dci.Users.Where(u => string.IsNullOrEmpty(u.LdapUserName)).ToList();
        }
    }

    public IActionResult OnPostSubmitCode(string code)
    {
        var claimCodeService = HttpContext.RequestServices.GetService<PhoneClaimCodeProviderService>();
        var validatedNumber = claimCodeService.ValidateClaimCodeForUser(code, HttpContext.User.Identity.Name);
        if (!string.IsNullOrEmpty(validatedNumber))
        {
            using (var dci = DataContext.Instance)
            {
                var user = dci.Users.Where(u => u.SignalMemberId == validatedNumber).FirstOrDefault();
                if (user == default(User))
                {
                    throw new Exception("User with specified phone number not found!");
                }
                user.LdapUserName = HttpContext.User.Identity.Name;
                dci.SaveChanges();
            }
        }
        else
        {
            throw new Exception("Invalid code provided!");
        }

        return RedirectToPage("/");
    }
}
