using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace Managing.Infrastructure.Databases.Migrations
{
    /// <inheritdoc />
    public partial class ChangeRequestIdToGuid : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            // Convert BundleBacktestRequests.RequestId from varchar to uuid
            // First, ensure all values are valid UUIDs or convert them
            migrationBuilder.Sql(@"
                UPDATE ""BundleBacktestRequests"" 
                SET ""RequestId"" = gen_random_uuid()::text 
                WHERE ""RequestId"" IS NULL OR ""RequestId"" = '' OR 
                      ""RequestId"" !~ '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$';
            ");

            // Now convert the column type using the USING clause
            migrationBuilder.Sql(@"
                ALTER TABLE ""BundleBacktestRequests"" 
                ALTER COLUMN ""RequestId"" TYPE uuid USING ""RequestId""::uuid;
            ");

            // Convert Backtests.RequestId from varchar to uuid
            // First, ensure all values are valid UUIDs or convert them  
            migrationBuilder.Sql(@"
                UPDATE ""Backtests"" 
                SET ""RequestId"" = gen_random_uuid()::text 
                WHERE ""RequestId"" IS NULL OR ""RequestId"" = '' OR 
                      ""RequestId"" !~ '^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$';
            ");

            // Now convert the column type using the USING clause
            migrationBuilder.Sql(@"
                ALTER TABLE ""Backtests"" 
                ALTER COLUMN ""RequestId"" TYPE uuid USING ""RequestId""::uuid;
            ");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            // Convert BundleBacktestRequests.RequestId from uuid back to varchar
            migrationBuilder.Sql(@"
                ALTER TABLE ""BundleBacktestRequests"" 
                ALTER COLUMN ""RequestId"" TYPE character varying(255) USING ""RequestId""::text;
            ");

            // Convert Backtests.RequestId from uuid back to varchar
            migrationBuilder.Sql(@"
                ALTER TABLE ""Backtests"" 
                ALTER COLUMN ""RequestId"" TYPE character varying(255) USING ""RequestId""::text;
            ");
        }
    }
}
