using Entities.Contracts;
using Entities.DTO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using TechHelper.Server.Services;
using System.Security.Claims;
using TechHelper.Services;


namespace TechHelper.Server.Controllers
{
	[Route("api/exam")]
	[ApiController]
	[Authorize]
	public class ExamController : ControllerBase
	{
		private readonly IExamService _examService;
		private readonly UserManager<User> _userManager;

		public ExamController(IExamService examService, UserManager<User> userManager)
		{
			_examService = examService;
			_userManager = userManager;
		}

		/// <summary>
		/// 创建一个新的考试/作业。
		/// </summary>
		/// <param name="examDto">考试/作业的数据传输对象。</param>
		/// <returns>新创建的考试/作业信息或错误信息。</returns>
		[HttpPost("add")]
		public async Task<IActionResult> AddExam([FromBody] AssignmentDto examDto)
		{
			var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			if (user == null) return NotFound("没有找到用户");
			examDto.CreatorId = user.Id;
			var result = await _examService.CreateExamAsync(examDto);

			if (result.Status)
			{
				return StatusCode(201, result.Result);
			}
			else
			{
				return BadRequest(result.Message);
			}
		}

		/// <summary>
		/// 提交作业。
		/// </summary>
		/// <param name="submissionDto">提交的数据传输对象。</param>
		/// <returns>提交结果或错误信息。</returns>
		[HttpPost("submission")]
		public async Task<IActionResult> SubmissionAssignment([FromBody] SubmissionDto submissionDto)
		{
			var result = await _examService.SubmissionAssignment(submissionDto);

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

		/// <summary>
		/// 根据ID获取考试/作业详情。
		/// </summary>
		/// <param name="id">考试/作业ID。</param>
		/// <returns>考试/作业详情或未找到错误。</returns>
		[HttpGet("{id:guid}")]
		public async Task<IActionResult> GetExamById(Guid id)
		{
			var result = await _examService.GetAsync(id);

			if (result.Status)
			{
				if (result.Result == null)
				{
					return NotFound("未找到指定的考试/作业。");
				}
				return Ok(result.Result);
			}
			else
			{
				if (result.Message.Contains("未找到") || result.Message.Contains("not found", StringComparison.OrdinalIgnoreCase))
				{
					return NotFound(result.Message);
				}
				return BadRequest(result.Message);
			}
		}

		/// <summary>
		/// 获取所有考试/作业的预览信息（教师获取自己创建的，学生获取自己需要提交的）。
		/// </summary>
		/// <returns>考试/作业预览列表或错误信息。</returns>
		[HttpGet("getAllPreview")]
		public async Task<IActionResult> GetAllExamPreview()
		{
			var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			if (user == null) return NotFound("没有找到用户");

			ApiResponse result;

			if (User.IsInRole("Teacher"))
			{
				result = await _examService.GetAllExamPreviewsAsync(user.Id);
			}
			else if (User.IsInRole("Student"))
			{
				result = await _examService.GetAllSubmissionAsync(user.Id);
			}
			else
			{
				return Forbid("你没有查看考试预览的权限。");
			}

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

		/// <summary>
		/// 获取学生的所有提交记录。
		/// </summary>
		/// <returns>提交记录列表或错误信息。</returns>
		[HttpGet("getAllSubmissions")]
		[Authorize(Roles = "Student")]
		public async Task<IActionResult> GetAllSubmission()
		{
			var user = await _userManager.FindByEmailAsync(User.Identity.Name);
			if (user == null) return NotFound("没有找到用户");

			var result = await _examService.GetAllSubmissionAsync(user.Id);

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

		/// <summary>
		/// 逻辑删除指定ID的考试/作业。
		/// </summary>
		/// <param name="id">要删除的考试/作业ID。</param>
		/// <returns>操作结果。</returns>
		[HttpDelete("delete/{id:guid}")]
		[Authorize(Roles = "Teacher")]
		public async Task<IActionResult> DeleteAsync(Guid id)
		{
			var deleteResult = await _examService.DeleteAsync(id);

			if (deleteResult.Status)
			{
				return NoContent();
			}
			else
			{
				if (deleteResult.Message.Contains("未找到") || deleteResult.Message.Contains("not found", StringComparison.OrdinalIgnoreCase))
				{
					return NotFound(deleteResult.Message);
				}
				return BadRequest(deleteResult.Message);
			}
		}


		/// <summary>
		/// 为指定学生指派作业
		/// </summary>
		/// <param name="AETSdto"></param>
		/// <returns></returns>
		[HttpPost("assignmentExamToStudent")]
		[Authorize(Roles = "Teacher")]
		public async Task<IActionResult> AssignmentExamToStudent([FromBody] AssigExamToStudentsDto AETSdto)
		{
			var result = await _examService.AssignmentToStudentsAsync(AETSdto);
			if (result.Status)
			{
				return Ok(result.Result);
			}
			else
			{
				return BadRequest(result.Message);
			}
		}


		/// <summary>
		/// 为所有学生指派作业
		/// </summary>
		/// <param name="AETSdto"></param>
		/// <returns></returns>
		[HttpPost("assignmentExamToStudent/{id:guid}")]
		[Authorize(Roles = "Teacher")]
		public async Task<IActionResult> AssignmentExamToAllStudentsAsync(Guid id)
		{
			var user = await _userManager.FindByEmailAsync(User.Identity.Name ?? "");
			var result = await _examService.AssignmentToAllStudentsAsync(id, user.Id);
			if (result.Status)
			{
				return Ok(result.Result);
			}
			else
			{
				return BadRequest(result.Message);
			}
		}
	}
}