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/submission")]
	[ApiController]
	[Authorize]

	public class SubmissionController : ControllerBase
	{
		private readonly UserManager<User> _userManager;
		private readonly ISubmissionService _submissionServices;

		public SubmissionController(UserManager<User> userManager, ISubmissionService submissionServices)
		{
			_userManager = userManager;
			_submissionServices = submissionServices;
		}



		/// <summary>
		/// 获取当前用户的所有错题。
		/// </summary>
		/// <returns>错题列表或错误信息。</returns>
		[HttpGet("getAllErrorQuestions")]
		public async Task<IActionResult> GetAllErrorQuestionsAsync()
		{
			var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			if (user == null)
			{
				return NotFound("未找到当前用户信息。");
			}

			var result = await _submissionServices.GetAllErrorQuestionsAsync(user.Id);

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

		/// <summary>
		/// 获取指定作业中当前用户的错题。
		/// </summary>
		/// <param name="assignmentId">作业ID。</param>
		/// <returns>错题列表或错误信息。</returns>
		[HttpGet("getAssignmentErrorQuestions/{assignmentId:guid}")]
		public async Task<IActionResult> GetAssignmentErrorQuestionsAsync(Guid assignmentId)
		{
			var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			if (user == null)
			{
				return NotFound("未找到当前用户信息。");
			}

			var result = await _submissionServices.GetAssignmentErrorQuestionsAsync(assignmentId, user.Id);

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

		/// <summary>
		/// 获取指定作业中当前用户的错题类型分布。
		/// </summary>
		/// <param name="assignmentId">作业ID。</param>
		/// <returns>错题类型分布数据。</returns>
		[HttpGet("getAssignmentErrorQuestionTypeDistribution/{assignmentId:guid}")]
		public async Task<IActionResult> GetAssignmentErrorQuestionTypeDisAsync(Guid assignmentId)
		{
			var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			if (user == null)
			{
				return NotFound("未找到当前用户信息。");
			}

			var result = await _submissionServices.GetAssignmentErrorQuestionTypeDisAsync(assignmentId, user.Id);

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

		/// <summary>
		/// 获取指定作业中所有学生的错题情况概述。
		/// </summary>
		/// <param name="assignmentId">作业ID。</param>
		/// <returns>每个学生的错题统计信息。</returns>
		[HttpGet("getAssignmentAllStudentsError/{assignmentId:guid}")]
		[Authorize(Roles = "Teacher")]
		public async Task<IActionResult> GetAssignmentAllStudentsError(Guid assignmentId)
		{
			// 假设当前用户是教师，如果需要验证，可以使用UserManager.IsInRoleAsync
			var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			if (user == null)
			{
				return NotFound("未找到当前用户信息。");
			}
			// TODO: 根据实际业务需求，可能需要验证当前用户是否为该作业的教师。
			// 例如： var isTeacherOfAssignment = await _assignmentService.IsTeacherOfAssignment(assignmentId, user.Id);

			var result = await _submissionServices.GetAssignmentAllStudentsError(assignmentId, user.Id); // 传入当前教师ID

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

		/// <summary>
		/// 获取指定作业中哪些学生做错了哪些题目。
		/// </summary>
		/// <param name="assignmentId">作业ID。</param>
		/// <returns>按题目分组的学生错题列表。</returns>
		[HttpGet("getQuestionErrorStudents/{assignmentId:guid}")]
		[Authorize(Roles = "Teacher")]
		public async Task<IActionResult> GetQuestionErrorStudents(Guid assignmentId)
		{
			var result = await _submissionServices.GetQuestionErrorStudents(assignmentId);

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

		/// <summary>
		/// 添加一次提交记录。
		/// </summary>
		/// <param name="model">提交的数据模型。</param>
		/// <returns>新创建的提交记录或错误信息。</returns>
		[HttpPost()]
		public async Task<IActionResult> AddAsync([FromBody] SubmissionDto model)
		{
			// 可以在这里获取当前用户ID并赋值给 model.StudentId，确保提交人信息正确
			// var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			// if (user == null) return NotFound("未找到当前用户信息。");
			// model.StudentId = user.Id;

			var result = await _submissionServices.AddAsync(model);

			if (result.Status)
			{
				// 如果成功，通常返回 201 Created，并包含新资源的URI
				// 但如果服务层只返回数据，也可以直接 Ok
				return StatusCode(201, result); // 建议返回 201 Created
			}
			else
			{
				return BadRequest(result.Message);
			}
		}

		/// <summary>
		/// 逻辑删除指定ID的提交记录。
		/// </summary>
		/// <param name="id">提交ID。</param>
		/// <returns>操作结果。</returns>
		[HttpDelete("delete/{id:guid}")]
		public async Task<IActionResult> DeleteAsync(Guid id)
		{
			// TODO: 在服务层或控制器层添加权限检查：确保删除者有权删除此提交（例如是提交者本人、相关教师或管理员）
			// var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			// if (user == null) return Unauthorized(); // 或 Forbidden

			var result = await _submissionServices.DeleteAsync(id);

			if (result.Status)
			{
				return NoContent(); // 204 No Content，表示删除成功但无内容返回
			}
			else
			{
				return BadRequest(result.Message);
			}
		}

		/// <summary>
		/// 获取所有提交记录（支持分页和查询）。
		/// </summary>
		/// <param name="query">查询参数，包含分页信息。</param>
		/// <returns>分页的提交记录列表。</returns>
		[HttpGet()]
		[Authorize(Roles = "Admin,Teacher")]
		public async Task<IActionResult> GetAllAsync([FromQuery] QueryParameter query)
		{
			var result = await _submissionServices.GetAllAsync(query);

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

		/// <summary>
		/// 根据ID获取单个提交记录。
		/// </summary>
		/// <param name="id">提交ID。</param>
		/// <returns>单个提交记录或未找到错误。</returns>
		[HttpGet("{id:guid}")]
		public async Task<IActionResult> GetAsync(Guid id)
		{
			var result = await _submissionServices.GetAsync(id);

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

		/// <summary>
		/// 更新提交记录。
		/// </summary>
		/// <param name="id">提交ID。</param>
		/// <param name="model">要更新的提交数据。</param>
		/// <returns>更新后的提交记录或错误信息。</returns>
		[HttpPut("update/{id:guid}")]
		public async Task<IActionResult> UpdateAsync(Guid id, [FromBody] SubmissionDto model)
		{
			if (id != model.Id) // 确保路径中的ID和模型中的ID一致
			{
				return BadRequest("路由ID与请求体中的ID不匹配。");
			}

			// TODO: 权限检查：确保更新者有权更新此提交
			// var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			// if (user == null) return Unauthorized();

			var result = await _submissionServices.UpdateAsync(model);

			if (result.Status)
			{
				return Ok(result);
			}
			else
			{

				return BadRequest(result.Message);
			}
		}


		[HttpPost("GradeExam")]
		[Authorize(Roles = "Teacher")]
		public async Task<IActionResult> GradeExam([FromBody] SubmissionTeacherUpdateDto model)
		{
			var result = await _submissionServices.GradeExam(model);
			if (result.Status)
			{
				return Ok(result);
			}
			else
			{
				return BadRequest(result.Message);
			}
		}

		/// <summary>
		/// 获取学生提交摘要。
		/// </summary>
		/// <param name="userId">用户ID。</param>
		/// <returns>学生提交摘要列表或错误信息。</returns>
		[HttpGet("getStudentSubmissionSummaries")]
		[Authorize(Roles = "Student")]
		public async Task<IActionResult> GetStudentSubmissionSummariesAsync()
		{
			var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			if (user == null)
			{
				return NotFound("未找到当前用户信息。");
			}

			var userId = user.Id; // 假设当前用户是学生，获取其ID
			var result = await _submissionServices.GetStudentSubmissionSummariesAsync(userId);

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

		/// <summary>
		/// 获取学生提交摘要。
		/// </summary>
		/// <param name="userId">用户ID。</param>
		/// <returns>学生提交摘要列表或错误信息。</returns>
		[HttpGet("getStudentSubmissionSummaries/{userId:guid}")]
		[Authorize(Roles = "Teacher")]
		public async Task<IActionResult> GetStudentSubmissionSummariesAsync(Guid userId)
		{
			var result = await _submissionServices.GetStudentSubmissionSummariesAsync(userId);

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

		/// <summary>
		/// 获取学生提交详情。
		/// </summary>
		/// <param name="submissionId">提交ID。</param>
		/// <returns>学生提交详情或错误信息。</returns>
		[HttpGet("getStudentSubmissionDetail/{submissionId:guid}")]
		public async Task<IActionResult> GetStudentSubmissionDetailAsync(Guid submissionId)
		{
			var result = await _submissionServices.GetStudentSubmissionDetailAsync(submissionId);

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