using adas_core.Application.Repositories.Interfaces;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.Filter;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Text.RegularExpressions;

namespace adas_core.Infrastructure.Repositories;

/// <summary>
/// Repository implementation for managing <see cref="Medicine"/> entities in MongoDB.
/// Provides CRUD operations, search, pagination, and aggregation capabilities specific to medicines.
/// </summary>
public class MedicineRepository : MongoRepository<Medicine>, IMedicineRepository
{
    private readonly ApiSettings _apiSettings;

    /// <summary>
    /// Initializes a new instance of the <see cref="MedicineRepository"/> class.
    /// </summary>
    /// <param name="apiSettings">The application API settings containing configuration values, including the collection name. Cannot be <see langword="null"/>.</param>
    /// <param name="database">The MongoDB database instance used to access the collection.</param>
    /// <exception cref="ArgumentNullException">Thrown when <paramref name="apiSettings"/> is <see langword="null"/>.</exception>
    public MedicineRepository(IOptions<ApiSettings> apiSettings, IMongoDatabase database) : base(database)
    {
        if (apiSettings == null) throw new ArgumentNullException(nameof(apiSettings));
        _apiSettings = apiSettings.Value;
    } //For testing



    /// <summary>
    /// Gets the name of the MongoDB collection used to store medicines.
    /// Falls back to the default "medicines" collection name when not configured in the API settings.
    /// </summary>
    /// <returns>The collection name retrieved from the API settings, or "medicines" if not configured.</returns>
    public override string GetCollectionName()
    {
        return _apiSettings.Medicines ?? "medicines";
    }

    /// <summary>
    /// Asynchronously retrieves a medicine whose <c>Codes</c> or <c>Notes</c> collection contains the specified code.
    /// </summary>
    /// <param name="code">The code or note text to search for within the medicine's codes or notes.</param>
    /// <returns>
    /// A <see cref="Task{Medicine}"/> representing the asynchronous operation.
    /// The task result contains the first <see cref="Medicine"/> matching the criteria, or <see langword="null"/> if no match is found.
    /// </returns>
    public async Task<Medicine?> GetMedicine(string code)
    {
        var result = await Collection.FindAsync(x => x.Codes.Contains(code) || x.Notes.Contains(code));

        return await result.FirstOrDefaultAsync();
    }


    /// <summary>
    /// Asynchronously retrieves all medicines whose <c>Codes</c> array contains any of the specified code values.
    /// </summary>
    /// <param name="codeNotes">A list of code strings to match against the medicine's codes. At least one code must match.</param>
    /// <returns>
    /// A <see cref="Task{List{Medicine}}"/> representing the asynchronous operation.
    /// The task result contains a list of matching <see cref="Medicine"/> objects. Returns an empty list if no matches are found.
    /// </returns>
    public async Task<List<Medicine>> GetMedicineByCodeOrNote(List<string> codeNotes)
    {
        var filter = Builders<Medicine>.Filter.AnyIn("Codes", codeNotes.ToArray());
        var result = await Collection.FindAsync(filter);

        return result.ToList();
    }

    /// <summary>
    /// Asynchronously retrieves a medicine by its exact name.
    /// </summary>
    /// <param name="name">The exact name of the medicine to search for.</param>
    /// <returns>
    /// A <see cref="Task{Medicine}"/> representing the asynchronous operation.
    /// The task result contains the <see cref="Medicine"/> if found; otherwise, <see langword="null"/>.
    /// </returns>
    public async Task<Medicine?> GetMedicineByName(string name)
    {
        var filter = Builders<Medicine>.Filter.Eq(p => p.Name, name);
        var result = await Collection.FindAsync(filter);

        return await result.FirstOrDefaultAsync();
    }

    /// <summary>
    /// Asynchronously retrieves all medicines stored in the collection.
    /// </summary>
    /// <returns>
    /// A <see cref="Task{List{Medicine}}"/> representing the asynchronous operation.
    /// The task result contains a list of all <see cref="Medicine"/> objects. Returns an empty list if the collection is empty.
    /// </returns>
    public async Task<List<Medicine>> GetAll()
    {
        var result = await Collection.FindAsync(_ => true);

        return result.ToList();
    }

    /// <summary>
    /// Asynchronously retrieves a medicine by its unique identifier.
    /// </summary>
    /// <param name="medicineId">The <see cref="ObjectId"/> of the medicine to retrieve.</param>
    /// <returns>
    /// A <see cref="Task{Medicine}"/> representing the asynchronous operation.
    /// The task result contains the <see cref="Medicine"/> if found; otherwise, <see langword="null"/>.
    /// </returns>
    public async Task<Medicine?> GetMedicineById(ObjectId medicineId)
    {
        var filter = Builders<Medicine>.Filter.Eq(p => p.Id, medicineId);
        var result = await Collection.FindAsync(filter);

        return await result.FirstOrDefaultAsync();
    }

    /// <summary>
    /// Asynchronously inserts a new medicine into the database and returns the inserted entity (looked up by name).
    /// </summary>
    /// <param name="medicine">The <see cref="Medicine"/> instance to insert.</param>
    /// <returns>
    /// A <see cref="Task{Medicine}"/> representing the asynchronous operation.
    /// The task result contains the newly inserted <see cref="Medicine"/> retrieved by its name, or <see langword="null"/> if the lookup fails.
    /// </returns>
    public async Task<Medicine?> PostMedicine(Medicine medicine)
    {
        await Collection.InsertOneAsync(medicine);
        var result = await Collection.FindAsync(v => v.Name == medicine.Name);

        return await result.FirstOrDefaultAsync();
    }

    /// <summary>
    /// Asynchronously updates an existing medicine in the database and returns the updated entity.
    /// </summary>
    /// <param name="medicine">The <see cref="Medicine"/> instance containing the updated values. The <see cref="ObjectId"/> is used to identify the document.</param>
    /// <returns>
    /// A <see cref="Task{Medicine}"/> representing the asynchronous operation.
    /// The task result contains the same <see cref="Medicine"/> instance that was passed in, after the update operation has been issued.
    /// </returns>
    public async Task<Medicine?> UpdateMedicine(Medicine medicine)
    {
        await UpdateOneAsync(medicine.Id, medicine);

        return medicine;
    }

    /// <summary>
    /// Asynchronously deletes a medicine from the database by its unique identifier.
    /// </summary>
    /// <param name="medicineId">The <see cref="ObjectId"/> of the medicine to delete.</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous delete operation.</returns>
    public async Task DeleteMedicineById(ObjectId medicineId)
    {
        var filter = Builders<Medicine>.Filter.Eq(po => po.Id, medicineId);

        await Collection.DeleteOneAsync(filter);
    }

    /// <summary>
    /// Retrieves a paginated, sorted, and filtered set of medicines based on the provided pagination filter.
    /// Results are sorted ascending by name. Supports optional case-insensitive regex match on the medicine name,
    /// and exact matches on code, type, and group.
    /// </summary>
    /// <param name="filter">The <see cref="PaginationFilter"/> containing pagination and filtering criteria.</param>
    /// <returns>
    /// An <see cref="IFindFluent{Medicine, Medicine}"/> instance that can be used to further refine and execute the query.
    /// When no filters are provided, all medicines are returned sorted by name.
    /// </returns>
    public IFindFluent<Medicine, Medicine> GetPaginatedMedicines(PaginationFilter filter)
    {
        // Crear variable con la clase que construye los filtros que necesitamos
        var filterBuilder = Builders<Medicine>.Filter;
        // Crear una lista de filtros que pueden venir de tu servicio
        var filters = new List<FilterDefinition<Medicine>>();
        // Ordenar los resultados por "time" en orden descendente
        var sort = Builders<Medicine>.Sort.Ascending("name");
        if (filter.FilteredRequest != null)
        {
            var requestFilter = filter.FilteredRequest;

            if (!string.IsNullOrWhiteSpace(requestFilter.MedicineName))
            {
                var escapedTextFilter = Regex.Escape(requestFilter.MedicineName);
                filters.Add(filterBuilder.Regex(m => m.Name,
                    new BsonRegularExpression(escapedTextFilter, "i")));
            }
            if (!string.IsNullOrWhiteSpace(requestFilter.MedicineCode))
                filters.Add(filterBuilder.AnyEq(m => m.Codes, requestFilter.MedicineCode));

            if (!string.IsNullOrWhiteSpace(requestFilter.MedicineType))
                filters.Add(filterBuilder.AnyEq(m => m.Type, requestFilter.MedicineType));

            if (!string.IsNullOrWhiteSpace(requestFilter.MedicineGroup))
                filters.Add(filterBuilder.AnyEq(m => m.Group, requestFilter.MedicineGroup));
        }

        if (filters.Count == 0)
            return Collection.Find(_ => true).Sort(sort);

        var combinedFilter = Builders<Medicine>.Filter.And(filters);

        return Collection
            .Find(combinedFilter)
            .Sort(sort);
    }

    /// <summary>
    /// Builds an aggregation pipeline that retrieves the distinct values of a specified array field
    /// from all medicines. The pipeline unwinds the field, groups by its value, sorts alphabetically,
    /// and projects the result with the original field name.
    /// </summary>
    /// <param name="field">The name of the array field on the <see cref="Medicine"/> document to retrieve distinct values for (for example, "Codes", "Type", or "Group").</param>
    /// <returns>
    /// An <see cref="IAggregateFluent{BsonDocument}"/> representing the aggregation pipeline that, when executed,
    /// yields documents containing the distinct values of the specified field.
    /// </returns>
    public IAggregateFluent<BsonDocument> GetDistinctFieldDataQuery(string field)
    {
        return Collection.Aggregate()
            .Unwind(field)
            .Group(new BsonDocument { { "_id", $"${field}" } })
            .Sort(new BsonDocument { { "_id", 1 } })
            .Project(new BsonDocument { { field, "$_id" }, { "_id", 0 } });
    }


    /// <summary>
    /// Retrieves all distinct medicine groups available in the collection.
    /// </summary>
    /// <returns>
    /// A <see cref="Task{List{String}}"/> representing the asynchronous operation,
    /// containing a list of distinct group names as strings.
    /// </returns>
    /// <exception cref="NotImplementedException">This method is not yet implemented.</exception>
    public Task<List<string>> GetAllGroups()
    {
        throw new NotImplementedException();
    }
}