using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ZpcBulletinBoard.Data;
using ZpcBulletinBoard.Models;

namespace ZpcBulletinBoard.Pages.SetupNew
{
    //[Authorize(Roles = "Administrator")]
    public class SetupModel : PageModel
    {
        private readonly ApplicationDbContext _context;
        private readonly UserManager<IdentityApplicationUser> _userManager;
        private readonly SignInManager<IdentityApplicationUser> _signInManager;
        private readonly RoleManager<IdentityApplicationRole> _roleManager;
        private readonly ILogger<SetupModel> _logger;

        public SetupModel(ApplicationDbContext context, UserManager<IdentityApplicationUser> userManager, SignInManager<IdentityApplicationUser> signInManager, ILogger<SetupModel> logger, RoleManager<IdentityApplicationRole> roleManager)
        {
            _context = context;
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
            _roleManager = roleManager;
        }

        public async Task<IActionResult> OnGetAsync()
        {
            //Ze obstajajo userji
            //if (_userManager.Users.Any())
            //    return RedirectToPage("/User/Login");

            var rolesDefinitions = new List<(string RoleName, string RoleDescription)>
            {
                ("User", "Uporabnik"),
                ("Administrator", "Administratorji"),
            };

            foreach (var roleDefinition in rolesDefinitions)
            {
                if (!_roleManager.RoleExistsAsync(roleDefinition.RoleName).Result)
                {
                    var role = new IdentityApplicationRole
                    {
                        Name = roleDefinition.RoleName,
                        Description = roleDefinition.RoleDescription
                    };

                    _roleManager.CreateAsync(role).Wait();
                }
            }

            var user = await _userManager.FindByNameAsync("admin");

            if (user == null)
            {
                IdentityApplicationUser identityApplicationUser = new IdentityApplicationUser
                {
                    Name = "Master",
                    Surname = "Admin",
                    UserName = "admin",
                    NormalizedUserName = "admin",
                    Email = "admin@domain.com",
                    NormalizedEmail = "admin@domain.com",
                    EmailConfirmed = true,
                    DateCreated = DateTime.Now,
                    DateValidUntil = DateTime.MaxValue,
                    PhoneNumber = "070777777",
                    PhoneNumberConfirmed = true,
                    Active = true,
                };

                var result = await _userManager.CreateAsync(identityApplicationUser, "*zpcBulletinBoard2024*");

                if (result.Succeeded)
                {
                    _userManager.AddToRoleAsync(identityApplicationUser, "Administrator").Wait();
                    //return RedirectToPage("/Administration/Users/Index");
                }
                else
                {
                    //ModelState.AddModelError("", string.Join(",", identityResult.Errors.Select(x => x.Description)));
                }
            }
            

            return RedirectToPage("/User/Login");
        }

        //public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        //{
        //    var user = await _userManager.GetUserAsync(User);

        //    await _signInManager.SignOutAsync();

        //    _logger.LogInformation($"Logout: {user.Name} {user.Surname} - {user.Company.Title}");
            
        //    if (returnUrl != null)
        //    {
        //        return LocalRedirect(returnUrl);
        //    }

        //    return RedirectToPage();
        //}
    }
}
