using Entities.Contracts;
using Entities.DTO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Net;
using System.Security.Claims;
using TechHelper.Services.Beta;
using TechHelper.Services;
using Entities.DTO.Class;

namespace TechHelper.Server.Controllers
{
	/// <summary>
	/// 班级管理控制器
	/// 处理班级相关的操作，如用户注册到班级、获取班级学生等
	/// </summary>
	[Route("api/class")]
	[ApiController]
	public class ClassController : ControllerBase
	{
		private TechHelper.Services.Beta.IClassService _classService;
		private UserManager<User> _userManager;

		/// <summary>
		/// 初始化班级控制器
		/// </summary>
		/// <param name="classService">班级服务</param>
		/// <param name="userManager">用户管理服务</param>
		public ClassController(TechHelper.Services.Beta.IClassService classService, UserManager<User> userManager)
		{
			_classService = classService;
			_userManager = userManager;
		}

		#region 班级基本信息CRUD操作

		/// <summary>
		/// 获取班级列表（支持搜索）
		/// </summary>
		/// <param name="query">查询参数</param>
		/// <returns>班级列表</returns>
		/// <response code="200">成功获取班级列表</response>
		/// <response code="400">获取失败</response>
		[HttpGet]
		[Authorize(Roles = "Teacher,Admin")]
		public async Task<IActionResult> GetAll([FromQuery] QueryParameter query)
		{
			var result = await _classService.GetAllAsync(query);

			if (!result.Status)
			{
				return BadRequest(result.Message);
			}

			return Ok(result.Result);
		}

		/// <summary>
		/// 根据ID获取班级详细信息
		/// </summary>
		/// <param name="id">班级ID</param>
		/// <returns>班级详细信息</returns>
		/// <response code="200">成功获取班级信息</response>
		/// <response code="400">班级未找到或获取失败</response>
		[HttpGet("{id}")]
		[Authorize(Roles = "Teacher,Admin")]
		public async Task<IActionResult> GetById(Guid id)
		{
			var result = await _classService.GetAsync(id);

			if (!result.Status)
			{
				return BadRequest(result.Message);
			}

			return Ok(result.Result);
		}

		/// <summary>
		/// 创建新班级
		/// </summary>
		/// <param name="model">班级数据传输对象</param>
		/// <returns>创建结果</returns>
		/// <response code="200">创建成功</response>
		/// <response code="400">创建失败</response>
		[HttpPost]
		public async Task<IActionResult> Create([FromBody] ClassDto model)
		{
			var result = await _classService.AddAsync(model);

			if (!result.Status)
			{
				return BadRequest(result.Message);
			}


			return Ok(result.Result);
		}


		[HttpPost("AdminCreate")]
		[Authorize(Roles = "Admin")]
		public async Task<IActionResult> Create([FromBody] ClassCreateDto dto)
		{
			var result = await _classService.AdminAddAsync(dto);

			if (!result.Status)
			{
				return BadRequest(result.Message);
			}


			return Ok(result.Result);
		}


		/// <summary>
		/// 更新班级信息
		/// </summary>
		/// <param name="model">班级数据传输对象</param>
		/// <returns>更新结果</returns>
		/// <response code="200">更新成功</response>
		/// <response code="400">更新失败</response>
		[HttpPut]
		[Authorize(Roles = "Admin")]
		public async Task<IActionResult> Update([FromBody] ClassDto model)
		{
			var result = await _classService.UpdateAsync(model);

			if (!result.Status)
			{
				return BadRequest(result.Message);
			}

			return Ok(result.Result);
		}

		/// <summary>
		/// 删除班级
		/// </summary>
		/// <param name="id">班级ID</param>
		/// <returns>删除结果</returns>
		/// <response code="200">删除成功</response>
		/// <response code="400">删除失败</response>
		[HttpDelete("{id}")]
		[Authorize(Roles = "Admin")]
		public async Task<IActionResult> Delete(Guid id)
		{
			var result = await _classService.DeleteAsync(id);

			if (!result.Status)
			{
				return BadRequest(result.Message);
			}

			return Ok(result.Message);
		}

		#endregion

		#region 班级用户管理

		/// <summary>
		/// 验证班级信息是否存在
		/// </summary>
		/// <param name="toClass">包含学校名称、年级和班级名称的数据传输对象</param>
		/// <returns>验证结果和班级信息</returns>
		/// <response code="200">验证成功，返回班级信息</response>
		/// <response code="400">验证失败</response>
		[HttpPost("validate")]
		[Authorize(Roles = "Student,Teacher,Admin")]
		public async Task<IActionResult> ValidateClassInfo(
			[FromBody] ClassValidDto toClass)
		{
			var result = await _classService.ValidateClassRegistration(toClass);

			if (!result.Status) return BadRequest(result.Message);

			return Ok(result.Result);
		}

		/// <summary>
		/// 用户注册到班级
		/// </summary>
		/// <param name="toClass">用户注册到班级的数据传输对象</param>
		/// <returns>操作结果</returns>
		/// <response code="200">注册成功</response>
		/// <response code="400">注册失败</response>
		[HttpPost("userRegiste")]
		[Authorize(Roles = "Student,Teacher,Admin")]
		public async Task<IActionResult> UserRegisterToClass(
			[FromBody] RegisterUserToClassDto toClass)
		{
			var result = await _classService.UserRegister(toClass);

			if (!result.Status) return BadRequest(result.Message);

			return Ok(result.Message);
		}

		/// <summary>
		/// 根据班级ID获取班级学生列表
		/// </summary>
		/// <param name="classId">班级ID</param>
		/// <returns>班级学生列表</returns>
		/// <response code="200">成功获取学生列表</response>
		/// <response code="400">班级未找到或获取失败</response>
		[HttpGet("students/{classId}")]
		[Authorize(Roles = "Teacher,Admin")]
		public async Task<IActionResult> GetClassStudentsById(Guid classId)
		{
			var result = await _classService.GetClassStudentsAsync(classId);

			if (!result.Status)
			{
				return BadRequest(result.Message);
			}
			return Ok(result.Result);
		}


		[HttpGet("classes")]
		[Authorize(Roles = "Teacher, Student")]
		public async Task<IActionResult> GetUserInjoinedClass()
		{
			var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			var userid = user.Id;

			var result = await _classService.GetUserInjoinedClasses(userid);
			if (result.Status)
				return Ok(result.Result);
			else
				return BadRequest(result.Message);
		}

		[HttpGet("injoint/{id:guid}")]
		[Authorize(Roles = "Teacher, Student")]
		public async Task<IActionResult> InjoinClass(Guid id)
		{
			var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			var userid = user.Id;

			var registerClass = new RegisterUserToClassDto { ClassId = id, UserId = userid, Role = user.Role ?? UserRoles.Student };

			var result = await _classService.UserRegister(registerClass);
			if (result.Status)
				return Ok(result.Result);
			else
				return BadRequest(result.Message);
		}

		#endregion
	}
}
