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

namespace adas_core.Infrastructure.Repositories;

public class LightBeaconRepository : MongoRepository<LightBeacon>, ILightBeaconRepository
{
    private readonly ApiSettings _apiSettings;
    

    public LightBeaconRepository(IMongoDatabase database, IOptions<ApiSettings> apiSettings) : base(database)
    {
        _apiSettings = apiSettings.Value;
    }

    public override string GetCollectionName()
    {
        return _apiSettings.LightBeacons;
    }

    public List<LightBeacon> GetLightBeaconInList(List<ObjectId> configurationRelayList)
    {
        var filterBuilder = Builders<LightBeacon>.Filter;

        var filter = filterBuilder.And(
            filterBuilder.In(r => r.Id, configurationRelayList));

        return Collection.Find(filter).ToList();
    }

    public async Task<LightBeacon?> GetById(ObjectId relayId)
    {
        try
        {
            var filter = Builders<LightBeacon>.Filter.Eq(x => x.Id, relayId);
            var result = await Collection.FindAsync(filter, null);
            return result.FirstOrDefault();
        }
        catch (Exception e)
        {
            Log.Error("Exception trying to get relay by id: {id}. Exception {e}", relayId, e);
            return null;
        }
    }

    public async Task<LightBeacon?> GetByName(string? requestRelayName)
    {
        var filterBuilder = Builders<LightBeacon>.Filter;

        var filter = filterBuilder.Eq(r => r.Name, requestRelayName);

        return await Collection.Find(filter).FirstOrDefaultAsync();
    }

    public async Task<LightBeacon?> InsertOneAsyncAndReturn(LightBeacon beacon)
    {
        try
        {
            await Collection.InsertOneAsync(beacon);
            return beacon;
        }
        catch (Exception ex)
        {
            Log.Error(ex.Message);
            return null;
        }
    }

    public IFindFluent<LightBeacon, LightBeacon> GetPaginatedRelays(PaginationFilter filter)
    {
        var filterBuilder = Builders<LightBeacon>.Filter;
        var sort = Builders<LightBeacon>.Sort.Ascending("name");
        var filters = new List<FilterDefinition<LightBeacon>>();

        if (filter.FilteredRequest == null)
            return CreateFindFluent(filters, sort);

        if (!string.IsNullOrWhiteSpace(filter.FilteredRequest.Text))
        {
            var textFilter = filter.FilteredRequest.Text;

            if (textFilter.Length > 100)
                throw new BadRequestException("Text filter too long");

            var textFilterEscaped = Regex.Escape(textFilter);

            filters.Add(
                filterBuilder.Regex(
                    p => p.Name,
                    new BsonRegularExpression(textFilterEscaped, "i")
                )
            );
        }

        return CreateFindFluent(filters, sort);
    }

    public Task<List<LightBeacon>> GetSearchByName(string textToSearch)
    {
        throw new NotImplementedException();
    }

    private IFindFluent<LightBeacon, LightBeacon> CreateFindFluent(List<FilterDefinition<LightBeacon>> filters, SortDefinition<LightBeacon> sort)
    {
        var combinedFilter = filters.Any()
            ? Builders<LightBeacon>.Filter.And(filters)
            : Builders<LightBeacon>.Filter.Empty; 
        return Collection.Find(combinedFilter).Sort(sort);
    }
}