using AutoMapper;
using Entities.Contracts;
using Entities.DTO;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.WebUtilities;
using SharedDATA.Api;
using System.Text;
using TechHelper.Features;

namespace TechHelper.Services
{
	public class UserRegistrationService : IUserRegistrationService
	{
		private readonly IUnitOfWork _work;
		private readonly IMapper _mapper;
		private readonly UserManager<User> _userManager; 
		private readonly IEmailSender _emailSender; 

		public UserRegistrationService(
			IUnitOfWork work,
			IMapper mapper,
			UserManager<User> userManager,
			IEmailSender emailSender) 
		{
			_work = work;
			_mapper = mapper;
			_userManager = userManager;
			_emailSender = emailSender;
		}

		public async Task<ApiResponse> RegisterNewUserAsync(UserForRegistrationDto registrationDto)
		{
			try
			{
				var existingUserByEmail = await _userManager.FindByEmailAsync(registrationDto.Email);
				if (existingUserByEmail != null)
				{
					return new ApiResponse("此电子邮件地址已被注册。");
				}

				var user = _mapper.Map<User>(registrationDto);

				user.UserName = registrationDto.Email;
				user.DisplayName = registrationDto.Name;
				user.EmailConfirmed = false; 

				var result = await _userManager.CreateAsync(user, registrationDto.Password);

				if (!result.Succeeded)
				{
					var errors = result.Errors.Select(e => e.Description).ToList();
					return new ApiResponse(false, errors);
				}

				var existingClass = await _work.GetRepository<Class>().GetFirstOrDefaultAsync(
					predicate: c => c.Number == registrationDto.Class && c.Grade == registrationDto.Grade);

				if (existingClass == null)
				{
					existingClass = new Class
					{
						Number = (byte)registrationDto.Class,
						Grade = (byte)registrationDto.Grade
					};
					await _work.GetRepository<Class>().InsertAsync(existingClass);
				}

				//if (registrationDto.Roles == UserRoles.Student)
				//{
				//	var classStudent = new ClassStudent
				//	{
				//		ClassId = existingClass.Id,
				//		StudentId = user.Id 
				//	};
				//	await _work.GetRepository<ClassStudent>().InsertAsync(classStudent);

				//	await _userManager.AddToRoleAsync(user, UserRoles.Student.ToString());
				//}
				//else if (registrationDto.Roles == UserRoles.Teacher)
				//{
				//	var classTeacher = new ClassTeacher
				//	{
				//		ClassId = existingClass.Id,
				//		TeacherId = user.Id 
				//	};
				//	await _work.GetRepository<ClassTeacher>().InsertAsync(classTeacher);

				//	await _userManager.AddToRoleAsync(user, UserRoles.Teacher.ToString());
				//}

				//var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);
				//var encodedToken = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(emailConfirmationToken));
				//var callbackUrl = QueryHelpers.AddQueryString(registrationDto.ClientURI, new Dictionary<string, string>
				//{
				//	{"token", encodedToken},
				//	{"email", user.Email} 
    //            });

				//try
				//{
				//	await _emailSender.SendEmailAsync(user.Email, "请确认您的邮箱", $"请点击此链接确认您的邮箱: {callbackUrl}");
				//}
				//catch (Exception ex)
				//{
				//	Console.Error.WriteLine($"发送邮箱确认邮件失败: {ex.Message}");
				//}


				if (await _work.SaveChangesAsync() > 0)
				{
					return new ApiResponse(true, "用户注册成功，班级关联和邮箱确认邮件已发送。");
				}
				else
				{
					return new ApiResponse("用户注册成功但班级关联失败。");
				}

			}
			catch (Exception ex)
			{
				Console.Error.WriteLine($"注册过程中发生错误: {ex.Message}");
				return new ApiResponse($"注册过程中发生错误: {ex.Message}");
			}
		}
	}
}