using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace Meezi.Infrastructure.Data.Migrations
{
    /// <inheritdoc />
    public partial class OrderDisplayNumber : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<int>(
                name: "DisplayNumber",
                table: "Orders",
                type: "integer",
                nullable: false,
                defaultValue: 0);

            migrationBuilder.Sql(
                """
                WITH numbered AS (
                    SELECT "Id",
                           ROW_NUMBER() OVER (PARTITION BY "CafeId" ORDER BY "CreatedAt", "Id") AS rn
                    FROM "Orders"
                )
                UPDATE "Orders" o
                SET "DisplayNumber" = n.rn
                FROM numbered n
                WHERE o."Id" = n."Id";
                """);

            migrationBuilder.CreateIndex(
                name: "IX_Orders_CafeId_DisplayNumber",
                table: "Orders",
                columns: new[] { "CafeId", "DisplayNumber" },
                unique: true);
        }

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

            migrationBuilder.DropColumn(
                name: "DisplayNumber",
                table: "Orders");
        }
    }
}
