using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional

namespace Baya.Infrastructure.Persistence.Migrations
{
    /// <inheritdoc />
    public partial class IdentitySessionsAndUserExtensions : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<DateTimeOffset>(
                name: "DeletedAt",
                schema: "usr",
                table: "Users",
                type: "datetimeoffset",
                nullable: true);

            migrationBuilder.AddColumn<string>(
                name: "Gender",
                schema: "usr",
                table: "Users",
                type: "nvarchar(10)",
                maxLength: 10,
                nullable: true);

            migrationBuilder.AddColumn<bool>(
                name: "IsActive",
                schema: "usr",
                table: "Users",
                type: "bit",
                nullable: false,
                defaultValue: false);

            migrationBuilder.AddColumn<string>(
                name: "NationalId",
                schema: "usr",
                table: "Users",
                type: "nvarchar(max)",
                nullable: true);

            migrationBuilder.AddColumn<DateTimeOffset>(
                name: "NationalIdVerifiedAt",
                schema: "usr",
                table: "Users",
                type: "datetimeoffset",
                nullable: true);

            migrationBuilder.AddColumn<string>(
                name: "PhoneHash",
                schema: "usr",
                table: "Users",
                type: "nvarchar(64)",
                maxLength: 64,
                nullable: true);

            migrationBuilder.AddColumn<DateTimeOffset>(
                name: "PhoneVerifiedAt",
                schema: "usr",
                table: "Users",
                type: "datetimeoffset",
                nullable: true);

            migrationBuilder.AddColumn<DateTimeOffset>(
                name: "ShahkarVerifiedAt",
                schema: "usr",
                table: "Users",
                type: "datetimeoffset",
                nullable: true);

            migrationBuilder.AddColumn<DateTimeOffset>(
                name: "GrantedAt",
                schema: "usr",
                table: "UserRoles",
                type: "datetimeoffset",
                nullable: false,
                defaultValue: new DateTimeOffset(new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)));

            migrationBuilder.AddColumn<int>(
                name: "GrantedById",
                schema: "usr",
                table: "UserRoles",
                type: "int",
                nullable: true);

            migrationBuilder.AddColumn<DateTimeOffset>(
                name: "RevokedAt",
                schema: "usr",
                table: "UserRoles",
                type: "datetimeoffset",
                nullable: true);

            migrationBuilder.CreateTable(
                name: "UserSessions",
                schema: "usr",
                columns: table => new
                {
                    Id = table.Column<long>(type: "bigint", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    UserId = table.Column<int>(type: "int", nullable: false),
                    RefreshTokenHash = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false),
                    DeviceInfo = table.Column<string>(type: "nvarchar(400)", maxLength: 400, nullable: true),
                    IpAddress = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true),
                    IsRevoked = table.Column<bool>(type: "bit", nullable: false, defaultValue: false),
                    RevokedAt = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
                    ExpiresAt = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
                    CreatedAt = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
                    ModifiedAt = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
                    CreatedById = table.Column<int>(type: "int", nullable: true),
                    ModifiedById = table.Column<int>(type: "int", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_UserSessions", x => x.Id);
                    table.ForeignKey(
                        name: "FK_UserSessions_Users_UserId",
                        column: x => x.UserId,
                        principalSchema: "usr",
                        principalTable: "Users",
                        principalColumn: "UserId",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.InsertData(
                schema: "ops",
                table: "PlatformConfigs",
                columns: new[] { "Id", "CreatedAt", "CreatedById", "DataType", "Description", "Key", "ModifiedAt", "ModifiedById", "Value" },
                values: new object[,]
                {
                    { 13L, new DateTimeOffset(new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)), null, "int", "Seconds a phone must wait before another OTP can be requested.", "auth_otp_resend_seconds", null, null, "120" },
                    { 14L, new DateTimeOffset(new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)), null, "int", "Wrong-code attempts allowed before OTP verification is refused until a fresh code.", "auth_otp_max_attempts", null, null, "5" },
                    { 15L, new DateTimeOffset(new DateTime(2026, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), new TimeSpan(0, 0, 0, 0, 0)), null, "int", "Refresh-token session lifetime in days.", "auth_session_ttl_days", null, null, "30" }
                });

            // Phone/email are encrypted at rest from this migration on, and reads now decrypt. Pre-b2
            // rows hold plaintext the decryptor would choke on — clear them (pre-launch dev/test
            // accounts only) and keep the seeded admin sign-in-able.
            migrationBuilder.Sql(
                "UPDATE [usr].[Users] SET [Email] = NULL, [NormalizedEmail] = NULL, [PhoneNumber] = NULL, [PhoneNumberConfirmed] = 0;");
            migrationBuilder.Sql(
                "UPDATE [usr].[Users] SET [IsActive] = 1 WHERE [UserName] = 'admin';");

            migrationBuilder.CreateIndex(
                name: "IX_Users_PhoneHash",
                schema: "usr",
                table: "Users",
                column: "PhoneHash",
                unique: true,
                filter: "[PhoneHash] IS NOT NULL");

            migrationBuilder.CreateIndex(
                name: "IX_UserRoles_GrantedById",
                schema: "usr",
                table: "UserRoles",
                column: "GrantedById");

            migrationBuilder.CreateIndex(
                name: "IX_UserSessions_RefreshTokenHash",
                schema: "usr",
                table: "UserSessions",
                column: "RefreshTokenHash",
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_UserSessions_UserId_IsRevoked",
                schema: "usr",
                table: "UserSessions",
                columns: new[] { "UserId", "IsRevoked" });

            migrationBuilder.AddForeignKey(
                name: "FK_UserRoles_Users_GrantedById",
                schema: "usr",
                table: "UserRoles",
                column: "GrantedById",
                principalSchema: "usr",
                principalTable: "Users",
                principalColumn: "UserId");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropForeignKey(
                name: "FK_UserRoles_Users_GrantedById",
                schema: "usr",
                table: "UserRoles");

            migrationBuilder.DropTable(
                name: "UserSessions",
                schema: "usr");

            migrationBuilder.DropIndex(
                name: "IX_Users_PhoneHash",
                schema: "usr",
                table: "Users");

            migrationBuilder.DropIndex(
                name: "IX_UserRoles_GrantedById",
                schema: "usr",
                table: "UserRoles");

            migrationBuilder.DeleteData(
                schema: "ops",
                table: "PlatformConfigs",
                keyColumn: "Id",
                keyValue: 13L);

            migrationBuilder.DeleteData(
                schema: "ops",
                table: "PlatformConfigs",
                keyColumn: "Id",
                keyValue: 14L);

            migrationBuilder.DeleteData(
                schema: "ops",
                table: "PlatformConfigs",
                keyColumn: "Id",
                keyValue: 15L);

            migrationBuilder.DropColumn(
                name: "DeletedAt",
                schema: "usr",
                table: "Users");

            migrationBuilder.DropColumn(
                name: "Gender",
                schema: "usr",
                table: "Users");

            migrationBuilder.DropColumn(
                name: "IsActive",
                schema: "usr",
                table: "Users");

            migrationBuilder.DropColumn(
                name: "NationalId",
                schema: "usr",
                table: "Users");

            migrationBuilder.DropColumn(
                name: "NationalIdVerifiedAt",
                schema: "usr",
                table: "Users");

            migrationBuilder.DropColumn(
                name: "PhoneHash",
                schema: "usr",
                table: "Users");

            migrationBuilder.DropColumn(
                name: "PhoneVerifiedAt",
                schema: "usr",
                table: "Users");

            migrationBuilder.DropColumn(
                name: "ShahkarVerifiedAt",
                schema: "usr",
                table: "Users");

            migrationBuilder.DropColumn(
                name: "GrantedAt",
                schema: "usr",
                table: "UserRoles");

            migrationBuilder.DropColumn(
                name: "GrantedById",
                schema: "usr",
                table: "UserRoles");

            migrationBuilder.DropColumn(
                name: "RevokedAt",
                schema: "usr",
                table: "UserRoles");
        }
    }
}
