using MongoDB.Bson;
using MongoDB.Driver;
using MongoMigrations.Core;

namespace adas_core.Infrastructure.Migrations.MongoMigrations;

/// <summary>
/// Represents a database migration responsible for updating the Point of Care configuration schema.
/// </summary>
/// <remarks>
/// The migration identifier prefix (U_0_1_2) indicates a specific ordering or version step within the migration sequence.
/// </remarks>
/// <!-- aidoc:v1 sig=4cbfeb5 -->
public class U_0_1_2_UpdatePointOfCareConfig : Migration
{
    /// <summary>
    /// Initializes a new instance of <see cref="U_0_1_2_UpdatePointOfCareConfig"/>, assigning a Description stating that it removes the PointOfCare configuration elements for poc, relay, camera, and beacon while keeping the placeholder for the new model, and passing 12 to the base constructor.
    /// </summary>
    /// <!-- aidoc:v1 sig=9495cc3 body=582e2e0 -->
    public U_0_1_2_UpdatePointOfCareConfig() : base(12)
    {
        Description =
            "Borra los elementos de configuracion de poc, relay, camera y beacon y deja el place holder del nuevo modelo";
    }

    /// <summary>
    /// Updates all point-of-care documents in the database by migrating their embedded configuration arrays (beacons, cameras, and relayList) to empty identifier list structures (beaconIdList, cameraIdList, and relayIdList), preserving the existing arrays' data not retained in this operation.
    /// </summary>
    /// <!-- aidoc-review:v1 severity=high kind=wrong_summary
    ///      "The summary claims data is 'preserved' through migration, but the code removes the existing 'beacons', 'cameras', and 'relayList' arrays entirely and replaces them with newly created empty BsonArrays—no data from the original arrays is retained or migrated." -->
    public override void Update()
        {
            var collection = Database.GetCollection<BsonDocument>("pointOfCares");
            
            var filter = Builders<BsonDocument>.Filter.Exists("configuration");
            var documents = collection.Find(filter).ToList();
    
            foreach (var doc in documents)
            {
                var configuration = doc["configuration"].AsBsonDocument;
    
                // Listas nuevas de IDs
                var beaconIdList = new BsonArray();
                var cameraIdList = new BsonArray();
                var relayIdList = new BsonArray();
    
                // 1. Procesar Beacons (si existen)
                if (configuration.Contains("beacons") && configuration["beacons"].IsBsonArray)
                {
                    configuration.Remove("beacons");
                }
    
                configuration["beaconIdList"] = beaconIdList;
    
                // 2. Procesar Cameras (si existen)
                if (configuration.Contains("cameras") && configuration["cameras"].IsBsonArray)
                {
                    configuration.Remove("cameras");
                }
    
                configuration["cameraIdList"] = cameraIdList;
    
                // 3. Procesar RelayList (si existen)
                if (configuration.Contains("relayList") && configuration["relayList"].IsBsonArray)
                {
                    configuration.Remove("relayList");
                }
    
                configuration["relayIdList"] = relayIdList;
    
                // Actualizar el documento en la base de datos
                collection.ReplaceOne(Builders<BsonDocument>.Filter.Eq("_id", doc["_id"]), doc);
            }
        }
}