using System.ComponentModel.DataAnnotations;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Graduation;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Jiaowu.Api.Controllers;

[ApiController]
[Authorize]
[Route("api/degree-awards")]
public sealed class DegreeAwardsController(
    AppDbContext db,
    ICurrentUserDataScope currentUserDataScope) : ControllerBase
{
    private const string Managers =
        SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin;
    private const string Reviewers = Managers + "," + SystemRoles.CollegeAdmin;

    [HttpGet("batches")]
    [Authorize(Roles = Reviewers)]
    public async Task<ActionResult> GetBatches(CancellationToken token)
    {
        var collegeId = RestrictedCollegeId();
        return Ok(await db.DegreeAwardBatches.AsNoTracking()
            .OrderByDescending(x => x.GraduationYear)
            .ThenByDescending(x => x.CreatedAt)
            .Select(x => new
            {
                x.Id,
                x.Name,
                x.GraduationYear,
                x.DegreeName,
                x.MinimumGradePoint,
                x.Status,
                x.Notes,
                x.CalculatedAt,
                x.PublishedAt,
                ResultCount = x.Results.Count(result =>
                    !collegeId.HasValue ||
                    result.Student!.AdministrativeClass!.Major!.CollegeId == collegeId),
                GrantedCount = x.Results.Count(result =>
                    (!collegeId.HasValue ||
                     result.Student!.AdministrativeClass!.Major!.CollegeId == collegeId) &&
                    result.Conclusion == DegreeAwardConclusion.Granted),
                NotGrantedCount = x.Results.Count(result =>
                    (!collegeId.HasValue ||
                     result.Student!.AdministrativeClass!.Major!.CollegeId == collegeId) &&
                    result.Conclusion == DegreeAwardConclusion.NotGranted),
                OverrideCount = x.Results.Count(result =>
                    (!collegeId.HasValue ||
                     result.Student!.AdministrativeClass!.Major!.CollegeId == collegeId) &&
                    result.IsOverridden)
            }).ToListAsync(token));
    }

    [HttpGet("batches/{id:guid}")]
    [Authorize(Roles = Reviewers)]
    public async Task<ActionResult> GetBatch(
        Guid id,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        [FromQuery] string? keyword = null,
        [FromQuery] DegreeAwardConclusion? conclusion = null,
        CancellationToken token = default)
    {
        page = Math.Max(page, 1);
        pageSize = Math.Clamp(pageSize, 10, 100);
        var batch = await db.DegreeAwardBatches.AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == id, token);
        if (batch is null) return NotFound();
        var collegeId = RestrictedCollegeId();
        var source = db.DegreeAwardResults.AsNoTracking()
            .Where(x => x.DegreeAwardBatchId == id);
        if (collegeId.HasValue)
            source = source.Where(x =>
                x.Student!.AdministrativeClass!.Major!.CollegeId == collegeId);

        var summary = await source
            .GroupBy(_ => 1)
            .Select(group => new
            {
                ResultCount = group.Count(),
                GrantedCount = group.Count(x =>
                    x.Conclusion == DegreeAwardConclusion.Granted),
                NotGrantedCount = group.Count(x =>
                    x.Conclusion == DegreeAwardConclusion.NotGranted),
                OverrideCount = group.Count(x => x.IsOverridden)
            })
            .FirstOrDefaultAsync(token);

        var normalizedKeyword = keyword?.Trim();
        if (!string.IsNullOrWhiteSpace(normalizedKeyword))
            source = source.Where(x =>
                x.Student!.StudentNumber.Contains(normalizedKeyword) ||
                x.Student.Name.Contains(normalizedKeyword) ||
                x.Student.AdministrativeClass!.Name.Contains(normalizedKeyword) ||
                x.Student.AdministrativeClass.Major!.Name.Contains(normalizedKeyword));
        if (conclusion.HasValue)
            source = source.Where(x => x.Conclusion == conclusion.Value);

        var total = await source.CountAsync(token);
        var items = await source.OrderBy(x => x.Student!.StudentNumber)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .Select(x => new
            {
                x.Id,
                x.StudentId,
                x.Student!.StudentNumber,
                x.Student.Name,
                ClassName = x.Student.AdministrativeClass!.Name,
                MajorName = x.Student.AdministrativeClass.Major!.Name,
                CollegeName = x.Student.AdministrativeClass.Major.College!.Name,
                x.AverageGradePoint,
                x.CalculatedConclusion,
                x.Conclusion,
                x.ExceptionReason,
                x.IsOverridden,
                x.ReviewComment,
                x.ReviewedAt
            }).ToListAsync(token);

        return Ok(new
        {
            batch.Id,
            batch.Name,
            batch.GraduationYear,
            batch.DegreeName,
            batch.MinimumGradePoint,
            batch.Status,
            batch.Notes,
            batch.CalculatedAt,
            batch.PublishedAt,
            ResultCount = summary?.ResultCount ?? 0,
            GrantedCount = summary?.GrantedCount ?? 0,
            NotGrantedCount = summary?.NotGrantedCount ?? 0,
            OverrideCount = summary?.OverrideCount ?? 0,
            Results = new
            {
                Items = items,
                Total = total,
                Page = page,
                PageSize = pageSize
            }
        });
    }

    [HttpPost("batches")]
    [Authorize(Roles = Managers)]
    public async Task<ActionResult> Create(
        DegreeAwardBatchRequest request,
        CancellationToken token)
    {
        var batch = new DegreeAwardBatch
        {
            Name = request.Name.Trim(),
            GraduationYear = request.GraduationYear,
            DegreeName = request.DegreeName.Trim(),
            MinimumGradePoint = request.MinimumGradePoint,
            Notes = request.Notes?.Trim()
        };
        db.DegreeAwardBatches.Add(batch);
        await db.SaveChangesAsync(token);
        return Created(string.Empty, new { batch.Id });
    }

    [HttpPost("batches/{id:guid}/calculate")]
    [Authorize(Roles = Managers)]
    public async Task<ActionResult> Calculate(Guid id, CancellationToken token)
    {
        var batch = await db.DegreeAwardBatches
            .FirstOrDefaultAsync(x => x.Id == id, token);
        if (batch is null) return NotFound();
        if (batch.Status != DegreeAwardBatchStatus.Draft)
            return ConflictProblem("已发布批次不能重新计算。");

        var auditCandidates = await db.GraduationAuditResults.AsNoTracking()
            .Where(x =>
                x.GraduationAuditBatch!.GraduationYear == batch.GraduationYear &&
                x.GraduationAuditBatch.Status == GraduationAuditBatchStatus.Published &&
                x.Conclusion == GraduationAuditConclusion.Eligible)
            .OrderByDescending(x => x.GraduationAuditBatch!.PublishedAt)
            .Select(x => new
            {
                x.Id,
                x.StudentId,
                StudentStatus = x.Student!.Status
            })
            .ToListAsync(token);
        var audits = auditCandidates
            .GroupBy(x => x.StudentId)
            .Select(x => x.First())
            .ToList();
        var gradePoints = await db.GradeRecords.AsNoTracking()
            .Where(x => x.GradeSheet!.Status == GradeSheetStatus.Published &&
                        x.GradePoint.HasValue)
            .Where(x => db.GraduationAuditResults.Any(audit =>
                audit.StudentId == x.StudentId &&
                audit.GraduationAuditBatch!.GraduationYear == batch.GraduationYear &&
                audit.GraduationAuditBatch.Status == GraduationAuditBatchStatus.Published &&
                audit.Conclusion == GraduationAuditConclusion.Eligible))
            .Select(x => new
            {
                x.StudentId,
                GradePoint = x.GradePoint!.Value,
                x.GradeSheet!.TeachingTask!.Course!.Credits
            }).ToListAsync(token);

        var gradePointsByStudent = gradePoints
            .GroupBy(x => x.StudentId)
            .ToDictionary(group => group.Key, group => group.ToList());

        await db.DegreeAwardResults
            .Where(x => x.DegreeAwardBatchId == id)
            .ExecuteDeleteAsync(token);

        foreach (var audit in audits)
        {
            var grades = gradePointsByStudent.GetValueOrDefault(audit.StudentId) ?? [];
            var credits = grades.Sum(x => x.Credits);
            var average = credits == 0
                ? 0
                : Math.Round(
                    grades.Sum(x => x.GradePoint * x.Credits) / credits,
                    2,
                    MidpointRounding.AwayFromZero);
            var conclusion = DegreeAwardRules.Evaluate(
                true, audit.StudentStatus, average, batch.MinimumGradePoint);
            var reason = audit.StudentStatus != StudentStatus.Graduated
                ? "学籍状态尚未转为毕业"
                : average < batch.MinimumGradePoint
                    ? $"平均绩点 {average:0.00}，低于批次要求 {batch.MinimumGradePoint:0.00}"
                    : string.Empty;
            db.DegreeAwardResults.Add(new DegreeAwardResult
            {
                DegreeAwardBatchId = batch.Id,
                StudentId = audit.StudentId,
                GraduationAuditResultId = audit.Id,
                AverageGradePoint = average,
                CalculatedConclusion = conclusion,
                Conclusion = conclusion,
                ExceptionReason = reason
            });
        }
        batch.CalculatedAt = DateTime.UtcNow;
        await db.SaveChangesAsync(token);
        return Ok(new { ResultCount = audits.Count });
    }

    [HttpPut("results/{id:guid}")]
    [Authorize(Roles = Reviewers)]
    public async Task<ActionResult> Review(
        Guid id,
        DegreeAwardDecisionRequest request,
        CancellationToken token)
    {
        var result = await db.DegreeAwardResults
            .Include(x => x.DegreeAwardBatch)
            .Include(x => x.Student)
            .ThenInclude(x => x!.AdministrativeClass)
            .ThenInclude(x => x!.Major)
            .FirstOrDefaultAsync(x => x.Id == id, token);
        if (result is null) return NotFound();
        if (result.DegreeAwardBatch!.Status != DegreeAwardBatchStatus.Draft)
            return ConflictProblem("已发布的授予结果不能修改。");
        var collegeId = RestrictedCollegeId();
        if (collegeId.HasValue &&
            result.Student!.AdministrativeClass!.Major!.CollegeId != collegeId)
            return Forbid();

        result.Conclusion = request.Conclusion;
        result.IsOverridden = request.Conclusion != result.CalculatedConclusion;
        result.ReviewComment = request.Comment.Trim();
        result.ReviewedAt = DateTime.UtcNow;
        await db.SaveChangesAsync(token);
        return NoContent();
    }

    [HttpPost("batches/{id:guid}/publish")]
    [Authorize(Roles = Managers)]
    public async Task<ActionResult> Publish(Guid id, CancellationToken token)
    {
        var batch = await db.DegreeAwardBatches.Include(x => x.Results)
            .FirstOrDefaultAsync(x => x.Id == id, token);
        if (batch is null) return NotFound();
        if (batch.Status != DegreeAwardBatchStatus.Draft)
            return ConflictProblem("该批次已经发布。");
        if (batch.Results.Count == 0)
            return ConflictProblem("没有可发布的学位授予审核结果。");
        batch.Status = DegreeAwardBatchStatus.Published;
        batch.PublishedAt = DateTime.UtcNow;
        await db.SaveChangesAsync(token);
        return NoContent();
    }

    [HttpGet("my-result")]
    [Authorize(Roles = SystemRoles.Student)]
    public async Task<ActionResult> GetMyResult(CancellationToken token)
    {
        var userId = currentUserDataScope.Current.UserId;
        var result = await db.DegreeAwardResults.AsNoTracking()
            .Where(x => x.Student!.UserId == userId &&
                        x.DegreeAwardBatch!.Status == DegreeAwardBatchStatus.Published)
            .OrderByDescending(x => x.DegreeAwardBatch!.GraduationYear)
            .ThenByDescending(x => x.DegreeAwardBatch!.PublishedAt)
            .Select(x => new
            {
                x.Id,
                BatchName = x.DegreeAwardBatch!.Name,
                x.DegreeAwardBatch.GraduationYear,
                x.DegreeAwardBatch.DegreeName,
                x.DegreeAwardBatch.MinimumGradePoint,
                x.Student!.StudentNumber,
                x.Student.Name,
                MajorName = x.Student.AdministrativeClass!.Major!.Name,
                x.AverageGradePoint,
                x.Conclusion,
                x.ExceptionReason,
                x.IsOverridden,
                x.ReviewComment,
                x.DegreeAwardBatch.PublishedAt
            }).FirstOrDefaultAsync(token);
        return Ok(result);
    }

    private Guid? RestrictedCollegeId()
    {
        var scope = currentUserDataScope.Current;
        return scope.IsInRole(SystemRoles.CollegeAdmin)
            ? scope.CollegeId ?? Guid.Empty
            : null;
    }

    private ActionResult ConflictProblem(string detail) => Conflict(new ProblemDetails
    {
        Title = "无法完成学位授予操作",
        Detail = detail,
        Status = StatusCodes.Status409Conflict
    });
}

public sealed record DegreeAwardBatchRequest(
    [Required, MinLength(3), MaxLength(120)] string Name,
    [Range(2000, 2200)] int GraduationYear,
    [Required, MinLength(2), MaxLength(80)] string DegreeName,
    [Range(typeof(decimal), "0", "5")] decimal MinimumGradePoint,
    [MaxLength(500)] string? Notes);

public sealed record DegreeAwardDecisionRequest(
    DegreeAwardConclusion Conclusion,
    [Required, MinLength(5), MaxLength(500)] string Comment);
