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>
public class U_0_1_2_UpdatePointOfCareConfig : Migration
{
    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>
    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);
            }
        }
}