using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace GameList.Data.Migrations
{
    /// <inheritdoc />
    public partial class AddAuthToPlayers : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<DateTimeOffset>(
                name: "LastLoginAt",
                table: "Players",
                type: "TEXT",
                nullable: true);

            migrationBuilder.AddColumn<string>(
                name: "NormalizedUsername",
                table: "Players",
                type: "TEXT",
                maxLength: 64,
                nullable: false,
                defaultValue: "");

            migrationBuilder.AddColumn<byte[]>(
                name: "PasswordHash",
                table: "Players",
                type: "BLOB",
                nullable: false,
                defaultValue: new byte[0]);

            migrationBuilder.AddColumn<byte[]>(
                name: "PasswordSalt",
                table: "Players",
                type: "BLOB",
                nullable: false,
                defaultValue: new byte[0]);

            migrationBuilder.AddColumn<string>(
                name: "Username",
                table: "Players",
                type: "TEXT",
                maxLength: 64,
                nullable: false,
                defaultValue: "");

            migrationBuilder.Sql(@"
UPDATE Players
SET Username = 'legacy-' || substr(Id,1,8),
    NormalizedUsername = lower('legacy-' || substr(Id,1,8))
WHERE coalesce(Username,'') = '' OR coalesce(NormalizedUsername,'') = '';

UPDATE Players
SET PasswordHash = X'', PasswordSalt = X''
WHERE (PasswordHash IS NULL OR length(PasswordHash)=0) OR (PasswordSalt IS NULL OR length(PasswordSalt)=0);
");

            migrationBuilder.CreateIndex(
                name: "IX_Players_NormalizedUsername",
                table: "Players",
                column: "NormalizedUsername",
                unique: true);
        }

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

            migrationBuilder.DropColumn(
                name: "LastLoginAt",
                table: "Players");

            migrationBuilder.DropColumn(
                name: "NormalizedUsername",
                table: "Players");

            migrationBuilder.DropColumn(
                name: "PasswordHash",
                table: "Players");

            migrationBuilder.DropColumn(
                name: "PasswordSalt",
                table: "Players");

            migrationBuilder.DropColumn(
                name: "Username",
                table: "Players");
        }
    }
}
