using adas_core.Domain.Enums;
using MongoDB.Bson;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace adas_core.Domain.Models;

/// <summary>
/// A JSON converter that handles the serialization and deserialization of <see cref="PatientAppointment"/> objects to and from JSON format.
/// </summary>
public class PatientAppointment : JsonConverter
{
    public ObjectId Id { get; set; }

    public ObjectId PatientId { get; set; }

    public Person? Patient { get; set; }

    public List<Timing> Timings { get; set; } = [];

    public DateTime? CreateTime { get; set; }

    public DateTime UpdateTime { get; set; }

    public Entity? PlacerOrder { get; set; }

    public Entity? FillerOrder { get; set; }

    public string? EventReason { get; set; }

    public string? AppointmentReason { get; set; }

    public string? AppointmentType { get; set; }

    public OperationType? AppointmentOperationType { get; set; }

    public OperationType? AppointmentStatus { get; set; }

    public double Duration { get; set; }

    public string? VisitNumber { get; set; }

    public string? PatientClass { get; set; }

    public bool EpisodeActivation { get; set; } = false;

    public Person? PlacerContact { get; set; }

    public Person? FillerContact { get; set; }

    public List<PatientAppointmentResourceGroup> ResourceGroups { get; set; } = [];

    public List<Allergies> Allergies { get; set; } = [];


    /// <summary>
    /// Applies the configured actions to each resource group, optionally pulling existing data from the provided database appointment.
    /// When <paramref name="apdb"/> is supplied and has a matching resource group, the actions are applied against the persisted data; otherwise the group is processed with a null source.
    /// </summary>
    /// <param name="apdb">The optional persisted <see cref="PatientAppointment"/> whose resource groups provide the source data for the actions. May be null or have fewer resource groups than the current list.</param>
    /// <returns>The list of <see cref="PatientAppointmentResourceGroup"/> instances with services, resources, locations, and personnel populated after applying the configured actions.</returns>
    public List<PatientAppointmentResourceGroup> ApplyResourceGroups(PatientAppointment? apdb = null)
        {
            var i = 0;
            ResourceGroups = ResourceGroups.Select(rg =>
            {
                var rgdb = apdb != null && apdb.ResourceGroups.Count > i ? apdb.ResourceGroups[i] : null;
    
                rg.Services = CodeAction.Apply(rgdb?.Services, rg.ServicesActions);
                rg.Resources = CodeAction.Apply(rgdb?.Resources, rg.ResourcesActions);
                rg.Locations = PatientLocationAction.Apply(rgdb?.Locations, rg.LocationsActions);
                rg.Personnel = PersonResourceAction.Apply(rgdb?.Personnel, rg.PersonnelActions);
                return rg;
            }).ToList();
            return ResourceGroups;
        }

    /// <summary>
    /// Determines whether the converter can convert the specified type, supporting only the <see cref="PatientAppointment"/> type.
    /// </summary>
    /// <param name="objectType">The type to check for converter support.</param>
    /// <returns><c>true</c> if <paramref name="objectType"/> is <see cref="PatientAppointment"/>; otherwise, <c>false</c>.</returns>
    public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(PatientAppointment);
        }

    /// <summary>
    /// Serializes the given value to JSON while excluding the "Id" property from the output. If the value is null, nothing is written to the writer.
    /// </summary>
    /// <param name="writer">The JSON writer to which the serialized output is written.</param>
    /// <param name="value">The object to serialize. A null value results in no output being written.</param>
    /// <param name="serializer">The JSON serializer used to perform the conversion.</param>
    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
        {
            if (value != null)
            {
                var jo = JObject.FromObject(value);
                jo.Property("Id")?.Remove();
                jo.WriteTo(writer);
            }
        }

    /// <summary>
    /// Reads the JSON representation of an object using the specified reader and serializer.
    /// This override is not yet implemented and currently throws a <see cref="NotImplementedException"/>.
    /// </summary>
    /// <param name="reader">The <see cref="JsonReader"/> used to read the JSON content.</param>
    /// <param name="objectType">The type of the object being deserialized.</param>
    /// <param name="existingValue">The existing value of the object being read, or <c>null</c> if no value exists.</param>
    /// <param name="serializer">The <see cref="JsonSerializer"/> invoking the converter.</param>
    /// <returns>An object representing the deserialized value.</returns>
    /// <exception cref="NotImplementedException">Always thrown, as the method has not been implemented.</exception>
    public override object ReadJson(JsonReader reader, Type objectType, object? existingValue,
            JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
}

/// <summary>
/// Represents a resource group that aggregates data and operations related to patient appointments.
/// </summary>
/// <remarks>
/// This class serves as a container or grouping mechanism for resources associated with managing patient appointment information.
/// </remarks>
public class PatientAppointmentResourceGroup
{
    public List<Code>? Services { get; set; }

    public List<Code>? Resources { get; set; }

    public List<PatientLocation>? Locations { get; set; }

    public List<PersonResource>? Personnel { get; set; }

    /**
     * ApiRequest resource actions
     */
    public List<CodeAction>? ServicesActions { get; set; }

    public List<CodeAction>? ResourcesActions { get; set; }
    public List<PatientLocationAction>? LocationsActions { get; set; }
    public List<PersonResourceAction>? PersonnelActions { get; set; }
}

/// <summary>
/// Represents allergy information, serving as a model or container for allergy-related data.
/// </summary>
public class Allergies
{
    public Code? AllergenType { get; set; }

    public Code? Allergen { get; set; }
}