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

namespace adas_core.Infrastructure.Migrations.MongoMigrations;

/// <summary>
/// Represents a database migration that updates the LanguageBarrier component to version 0.1.3.
/// </summary>
/// <!-- aidoc:v1 sig=8c1ced1 -->
public class U_0_1_3_UpdateLanguageBarrier : Migration
{
    /// <summary>
    /// Initializes a new instance of the <see cref="U_0_1_3_UpdateLanguageBarrier"/> class, passing identifier <c>13</c> to the base constructor and assigning the Description property to describe the removal of poc, relay, camera and beacon configuration elements for the new model.
    /// </summary>
    /// <!-- aidoc:v1 sig=5e97941 body=582e2e0 -->
    public U_0_1_3_UpdateLanguageBarrier() : base(13)
    {
        Description =
            "Borra los elementos de configuracion de poc, relay, camera y beacon y deja el place holder del nuevo modelo";
    }

    /// <summary>
    /// Converts the <c>languageBarrier</c> field in the <c>patients</c> and <c>admissions</c> collections from a scalar value into a <see cref="MongoDB.Bson.BsonArray"/>, preserving the original value as the first element when it is not null. Documents where the field is already an array are left untouched, and null values are replaced with an empty array.
    /// </summary>
    /// <!-- aidoc:v1 sig=2ec5b05 body=932d7f9 -->
    public override void Update()
    {
        string[] collectionsToUpdate = { "patients", "admissions" };

        foreach (var collectionName in collectionsToUpdate)
        {
            var collection = Database.GetCollection<BsonDocument>(collectionName);

            // Filtramos documentos donde languageBarrier existe y NO es ya un array
            var filter = Builders<BsonDocument>.Filter.And(
                Builders<BsonDocument>.Filter.Exists("languageBarrier"),
                Builders<BsonDocument>.Filter.Not(Builders<BsonDocument>.Filter.Type("languageBarrier", BsonType.Array))
            );

            var documents = collection.Find(filter).ToList();

            foreach (var doc in documents)
            {
                var currentValue = doc["languageBarrier"];
                BsonArray newArray = new BsonArray();

                // Si el valor actual no es nulo, lo añadimos como primer elemento del array
                if (!currentValue.IsBsonNull)
                {
                    newArray.Add(currentValue);
                }

                // Actualizamos el campo en el documento Bson
                doc["languageBarrier"] = newArray;

                // Guardamos los cambios en la base de datos
                collection.ReplaceOne(Builders<BsonDocument>.Filter.Eq("_id", doc["_id"]), doc);
            }
        }
    }
}