using Entities.Contracts;
using Entities.DTO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using TechHelper.Context;
using TechHelper.Repository;
using SharedDATA.Api;
using System.Security.Claims;
using TechHelper.Services.Beta;

namespace TechHelper.Server.Controllers
{
    [Route("api/student-submission-detail")]
    [ApiController]
    [Authorize]
    public class StudentSubmissionDetailController : ControllerBase
    {
    private readonly ISubmissionDetailService _studentSubmissionDetailService;
    private readonly UserManager<User> _userManager;
    private readonly IUnitOfWork _unitOfWork;

    public StudentSubmissionDetailController(
		ISubmissionDetailService studentSubmissionDetailService,
        UserManager<User> userManager,
        IUnitOfWork unitOfWork)
    {
        _studentSubmissionDetailService = studentSubmissionDetailService;
        _userManager = userManager;
        _unitOfWork = unitOfWork;
    }

        /// <summary>
        /// 获取学生提交的详细信息
        /// </summary>
        /// <param name="submissionId">提交ID</param>
        /// <returns>学生提交详细信息</returns>
        [HttpGet("{submissionId:guid}")]
        public async Task<IActionResult> GetSubmissionDetail(Guid submissionId)
        {
            try
            {
                // 验证用户权限 - 只有学生本人或教师可以查看
                var user = await _userManager.FindByEmailAsync(User.Identity.Name);
                if (user == null)
                {
                    return NotFound("未找到用户信息");
                }

                var submission = await _unitOfWork.GetRepository<Submission>()
                    .GetFirstOrDefaultAsync(predicate: s => s.Id == submissionId);

                if (submission == null)
                {
                    return NotFound("未找到指定的提交记录");
                }

                // 检查权限：学生只能查看自己的提交，教师可以查看所有提交
                if (user.Id != submission.StudentId && !User.IsInRole("Teacher"))
                {
                    return Forbid("您没有权限查看此提交记录");
                }

                var result = await _studentSubmissionDetailService.GetBySubmissionIdAsync(submissionId);

                if (result.Status)
                {
                    return Ok(result.Result);
                }
                else
                {
                    return BadRequest(result.Message);
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"获取学生提交详细信息失败: {ex.Message}");
            }
        }
    }
}
