using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace UniVerse.Infrastructure.Migrations
{
    /// <inheritdoc />
    public partial class UserRolesJoinTable : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "user_roles",
                columns: table => new
                {
                    user_id = table.Column<int>(type: "integer", nullable: false),
                    role = table.Column<int>(type: "integer", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_user_roles", x => new { x.user_id, x.role });
                    table.ForeignKey(
                        name: "FK_user_roles_users_user_id",
                        column: x => x.user_id,
                        principalTable: "users",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.Sql("""
                INSERT INTO user_roles (user_id, role)
                SELECT id, role FROM users;
                """);

            migrationBuilder.DropColumn(
                name: "role",
                table: "users");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<int>(
                name: "role",
                table: "users",
                type: "integer",
                nullable: false,
                defaultValue: 0);

            migrationBuilder.Sql("""
                UPDATE users
                SET role = COALESCE((
                    SELECT MIN(ur.role)
                    FROM user_roles ur
                WHERE ur.user_id = users.id
                ), 0);
                """);

            migrationBuilder.DropTable(
                name: "user_roles");

        }
    }
}
