using Entities.Contracts;
using Entities.DTO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using TechHelper.Services;
using TechHelper.Services.Beta;

namespace TechHelper.Server.Controllers
{
	[Route("api/user")]
	[ApiController]
	[Authorize]
	public class UserController : ControllerBase
	{
		private readonly IUserSerivces _userSerivces;
		private readonly IClassService _classService;
		private readonly UserManager<User> _userManager;

		public UserController(IClassService classService, UserManager<User> userManager, IUserSerivces userSerivces)
		{
			_classService = classService;
			_userManager = userManager;
			_userSerivces = userSerivces;
		}

		/// <summary>
		/// 获取指定用户信息
		/// </summary>
		/// <param name="id">用户ID</param>
		/// <returns>用户信息</returns>
		[HttpGet("{id}")]
		public async Task<IActionResult> GetUserById(Guid id)
		{
			var result = await _userSerivces.GetAsync(id);
			if (!result.Status)
			{
				return NotFound(result);
			}
			return Ok(result);
		}

		/// <summary>
		/// 获取所有用户列表
		/// </summary>
		/// <param name="query">查询参数</param>
		/// <returns>用户列表</returns>
		[HttpGet]
		public async Task<IActionResult> GetAllUsers([FromQuery] QueryParameter query)
		{
			var result = await _userSerivces.GetAllAsync(query);
			if (!result.Status)
			{
				return BadRequest(result);
			}
			return Ok(result);
		}

		/// <summary>
		/// 添加新用户
		/// </summary>
		/// <param name="userDto">用户数据</param>
		/// <returns>操作结果</returns>
		[HttpPost]
		public async Task<IActionResult> AddUser([FromBody] UserDto userDto)
		{
			if (!ModelState.IsValid)
			{
				return BadRequest(ModelState);
			}

			var result = await _userSerivces.AddAsync(userDto);
			if (!result.Status)
			{
				return BadRequest(result);
			}
			return CreatedAtAction(nameof(GetUserById), new { id = userDto.Id }, result);
		}

		/// <summary>
		/// 更新用户信息
		/// </summary>
		/// <param name="id">用户ID</param>
		/// <param name="userDto">用户数据</param>
		/// <returns>操作结果</returns>
		[HttpPut("{id}")]
		public async Task<IActionResult> UpdateUser(Guid id, [FromBody] UserDto userDto)
		{
			if (!ModelState.IsValid)
			{
				return BadRequest(ModelState);
			}

			if (id != userDto.Id)
			{
				return BadRequest("用户ID不匹配");
			}

			var result = await _userSerivces.UpdateAsync(userDto);
			if (!result.Status)
			{
				return BadRequest(result);
			}
			return Ok(result);
		}

		/// <summary>
		/// 删除用户
		/// </summary>
		/// <param name="id">用户ID</param>
		/// <returns>操作结果</returns>
		[HttpDelete("{id}")]
		public async Task<IActionResult> DeleteUser(Guid id)
		{
			var result = await _userSerivces.DeleteAsync(id);
			if (!result.Status)
			{
				return BadRequest(result);
			}
			return Ok(result);
		}

		/// <summary>
		/// 获取学生详细信息
		/// </summary>
		/// <param name="userId">用户ID</param>
		/// <returns>学生详细信息</returns>
		[HttpGet("student/{userId}")]
		public async Task<IActionResult> GetStudentDetailInfo(Guid userId)
		{
			var result = await _userSerivces.GetStudentDetailInfo(userId);
			if (!result.Status)
			{
				return NotFound(result);
			}
			return Ok(result);
		}

		/// <summary>
		/// 验证用户信息
		/// </summary>
		/// <param name="userId">用户ID</param>
		/// <returns>验证结果</returns>
		[HttpPost("verify/{userId}")]
		public async Task<IActionResult> VerifyUserInformation(Guid userId)
		{
			var result = await _userSerivces.VerifyUserInformation(userId);
			if (!result.Status)
			{
				return BadRequest(result);
			}
			return Ok(result);
		}

		/// <summary>
		/// 恢复用户角色信息
		/// </summary>
		/// <returns>操作结果</returns>
		[HttpGet("restoreUserRole")]
		public async Task<IActionResult> RestoreUserRole()
		{
			var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			if (user == null) return NotFound("用户不存在");
			
			if (User.IsInRole("Teacher") || User.IsInRole("Student"))
				return Ok(new ApiResponse(true, "用户角色已正确设置"));

			var result = await _userSerivces.RestoreUserRoleInformation(user);
			if (result.Status)
				return Ok(result);
			else
				return Unauthorized(result);
		}

		/// <summary>
		/// 注册新用户
		/// </summary>
		/// <param name="registrationDto">注册数据</param>
		/// <returns>注册结果</returns>
		[HttpPost("register")]
		[AllowAnonymous]
		public async Task<IActionResult> RegisterNewUser([FromBody] UserForRegistrationDto registrationDto)
		{
			if (!ModelState.IsValid)
			{
				return BadRequest(ModelState);
			}

			var result = await _userSerivces.RegisterNewUserAsync(registrationDto);
			if (!result.Status)
			{
				return BadRequest(result);
			}
			return Ok(result);
		}

		/// <summary>
		/// 获取指定用户信息（旧接口）
		/// </summary>
		/// <param name="toClass">班级注册数据</param>
		/// <returns>操作结果</returns>
		[HttpPost("get")]
		[Obsolete("请使用 GET /api/user/{id} 接口")]
		public async Task<IActionResult> GetAsync([FromBody] UserRegistrationToClassDto toClass)
		{
			return Ok(new ApiResponse(false, "此接口已弃用，请使用新的接口"));
		}
	}
}
