using MemberCenter.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace MemberCenter.Infrastructure.Persistence.Migrations
{
    /// <inheritdoc />
    [DbContext(typeof(MemberCenterDbContext))]
    [Migration("20260417043000_ChangeUserAddressDefaultToSinglePerUser")]
    public partial class ChangeUserAddressDefaultToSinglePerUser : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql("""
                WITH ranked_defaults AS (
                    SELECT "Id",
                           ROW_NUMBER() OVER (
                               PARTITION BY "UserId"
                               ORDER BY "UpdatedAt" DESC, "CreatedAt" DESC, "Id"
                           ) AS rn
                    FROM user_addresses
                    WHERE "IsDefault" = true
                )
                UPDATE user_addresses ua
                SET "IsDefault" = false,
                    "UpdatedAt" = now()
                FROM ranked_defaults rd
                WHERE ua."Id" = rd."Id"
                  AND rd.rn > 1;
                """);

            migrationBuilder.Sql("""
                WITH users_without_default AS (
                    SELECT ua."UserId"
                    FROM user_addresses ua
                    GROUP BY ua."UserId"
                    HAVING BOOL_OR(ua."IsDefault") = false
                ),
                replacement AS (
                    SELECT ranked."Id"
                    FROM (
                        SELECT ua."Id",
                               ua."UserId",
                               ROW_NUMBER() OVER (
                                   PARTITION BY ua."UserId"
                                   ORDER BY ua."UpdatedAt" DESC, ua."CreatedAt" DESC, ua."Id"
                               ) AS rn
                        FROM user_addresses ua
                        INNER JOIN users_without_default uwd ON uwd."UserId" = ua."UserId"
                    ) ranked
                    WHERE ranked.rn = 1
                )
                UPDATE user_addresses ua
                SET "IsDefault" = true,
                    "UpdatedAt" = now()
                FROM replacement r
                WHERE ua."Id" = r."Id";
                """);

            migrationBuilder.DropIndex(
                name: "ux_user_addresses_default_per_usage",
                table: "user_addresses");

            migrationBuilder.CreateIndex(
                name: "ux_user_addresses_default_per_user",
                table: "user_addresses",
                columns: new[] { "UserId", "IsDefault" },
                unique: true,
                filter: "\"IsDefault\" = true");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropIndex(
                name: "ux_user_addresses_default_per_user",
                table: "user_addresses");

            migrationBuilder.CreateIndex(
                name: "ux_user_addresses_default_per_usage",
                table: "user_addresses",
                columns: new[] { "UserId", "Usage", "IsDefault" },
                unique: true,
                filter: "\"IsDefault\" = true");
        }
    }
}
