using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace Jiaowu.Api.Infrastructure.Persistence.Migrations.MySql
{
    /// <inheritdoc />
    public partial class PersistExperimentCourseGrades : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "ExperimentCourseGrades",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "char(36)", nullable: false),
                    TeachingTaskId = table.Column<Guid>(type: "char(36)", nullable: false),
                    StudentId = table.Column<Guid>(type: "char(36)", nullable: false),
                    WeightedAverageScore = table.Column<decimal>(type: "decimal(5,1)", precision: 5, scale: 1, nullable: true),
                    TotalWeight = table.Column<decimal>(type: "decimal(8,1)", precision: 8, scale: 1, nullable: false),
                    PublishedProjectCount = table.Column<int>(type: "int", nullable: false),
                    RefreshedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
                    CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
                    UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ExperimentCourseGrades", x => x.Id);
                    table.ForeignKey(
                        name: "FK_ExperimentCourseGrades_Students_StudentId",
                        column: x => x.StudentId,
                        principalTable: "Students",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_ExperimentCourseGrades_TeachingTasks_TeachingTaskId",
                        column: x => x.TeachingTaskId,
                        principalTable: "TeachingTasks",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                })
                .Annotation("MySQL:Charset", "utf8mb4");

            migrationBuilder.CreateIndex(
                name: "IX_ExperimentCourseGrades_StudentId",
                table: "ExperimentCourseGrades",
                column: "StudentId");

            migrationBuilder.CreateIndex(
                name: "IX_ExperimentCourseGrades_TeachingTaskId_StudentId",
                table: "ExperimentCourseGrades",
                columns: new[] { "TeachingTaskId", "StudentId" },
                unique: true);

            migrationBuilder.Sql(
                """
                INSERT INTO `ExperimentCourseGrades`
                    (`Id`, `TeachingTaskId`, `StudentId`, `WeightedAverageScore`,
                     `TotalWeight`, `PublishedProjectCount`, `RefreshedAt`,
                     `CreatedAt`, `UpdatedAt`)
                SELECT
                    UUID(),
                    project.`TeachingTaskId`,
                    record.`StudentId`,
                    CASE
                        WHEN COUNT(*) = (
                            SELECT COUNT(*)
                            FROM `ExperimentGradeSheets` AS all_sheet
                            INNER JOIN `ExperimentProjects` AS all_project
                                ON all_project.`Id` = all_sheet.`ExperimentProjectId`
                            WHERE all_sheet.`Status` = 4
                              AND all_project.`TeachingTaskId` = project.`TeachingTaskId`)
                         AND SUM(CASE WHEN record.`TotalScore` IS NULL THEN 1 ELSE 0 END) = 0
                        THEN ROUND(
                            SUM(record.`TotalScore` * sheet.`ContributionWeight`) /
                            SUM(sheet.`ContributionWeight`), 1)
                        ELSE NULL
                    END,
                    (
                        SELECT COALESCE(SUM(all_sheet.`ContributionWeight`), 0)
                        FROM `ExperimentGradeSheets` AS all_sheet
                        INNER JOIN `ExperimentProjects` AS all_project
                            ON all_project.`Id` = all_sheet.`ExperimentProjectId`
                        WHERE all_sheet.`Status` = 4
                          AND all_project.`TeachingTaskId` = project.`TeachingTaskId`),
                    (
                        SELECT COUNT(*)
                        FROM `ExperimentGradeSheets` AS all_sheet
                        INNER JOIN `ExperimentProjects` AS all_project
                            ON all_project.`Id` = all_sheet.`ExperimentProjectId`
                        WHERE all_sheet.`Status` = 4
                          AND all_project.`TeachingTaskId` = project.`TeachingTaskId`),
                    UTC_TIMESTAMP(6), UTC_TIMESTAMP(6), UTC_TIMESTAMP(6)
                FROM `ExperimentGradeRecords` AS record
                INNER JOIN `ExperimentGradeSheets` AS sheet
                    ON sheet.`Id` = record.`ExperimentGradeSheetId`
                INNER JOIN `ExperimentProjects` AS project
                    ON project.`Id` = sheet.`ExperimentProjectId`
                WHERE sheet.`Status` = 4
                GROUP BY project.`TeachingTaskId`, record.`StudentId`;
                """);
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "ExperimentCourseGrades");
        }
    }
}
