using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace CalledIt.DataAccess.Migrations
{
    /// <inheritdoc />
    public partial class AddUserCompetitionStats : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "UserCompetitionStats",
                columns: table => new
                {
                    UserId = table.Column<int>(type: "integer", nullable: false),
                    CompetitionId = table.Column<int>(type: "integer", nullable: false),
                    TotalPoints = table.Column<int>(type: "integer", nullable: false),
                    BetsPlaced = table.Column<int>(type: "integer", nullable: false),
                    BetsEvaluated = table.Column<int>(type: "integer", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_UserCompetitionStats", x => new { x.UserId, x.CompetitionId });
                    table.ForeignKey(
                        name: "FK_UserCompetitionStats_Competitions_CompetitionId",
                        column: x => x.CompetitionId,
                        principalTable: "Competitions",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_UserCompetitionStats_Users_UserId",
                        column: x => x.UserId,
                        principalTable: "Users",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_UserCompetitionStats_CompetitionId_TotalPoints",
                table: "UserCompetitionStats",
                columns: new[] { "CompetitionId", "TotalPoints" });

            // Backfill stats from existing bets data
            migrationBuilder.Sql(@"
                INSERT INTO ""UserCompetitionStats"" (""UserId"", ""CompetitionId"", ""TotalPoints"", ""BetsPlaced"", ""BetsEvaluated"")
                SELECT
                    b.""UserId"",
                    m.""CompetitionId"",
                    COALESCE(SUM(b.""Points""), 0) AS ""TotalPoints"",
                    COUNT(*) AS ""BetsPlaced"",
                    COUNT(b.""Points"") AS ""BetsEvaluated""
                FROM ""Bets"" b
                JOIN ""Matches"" m ON b.""MatchId"" = m.""Id""
                GROUP BY b.""UserId"", m.""CompetitionId"";
            ");
        }

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