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 Newtonsoft.Json;
using Serilog;
using System.Text.RegularExpressions;

namespace adas_core.Infrastructure.Repositories;

public class CameraRepository : MongoRepository<Camera>, ICameraRepository
{
    private readonly ApiSettings _apiSettings;
    

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

    public override string GetCollectionName()
    {
       return _apiSettings.Cameras;
    }
    
    public async Task<Camera?> GetById(ObjectId cameraId)
    {
        try
        {
            var filter = Builders<Camera>.Filter.Eq(x => x.Id, cameraId);
            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}", cameraId, e);
            return null;
        }
    }

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

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

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

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

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

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

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

        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 safeInput = Regex.Escape(textFilter);

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

        return CreateFindFluent(filters, sort);
    }

    public async Task<Camera?> InsertOneCamera(Camera camera)
    {
        try
        {
            await Collection.InsertOneAsync(camera);
            return await GetById(camera.Id);
        }
        catch (Exception ex)
        {
            Log.Error("Error inserting camera: {camera}. Exception: {ex}",
                JsonConvert.SerializeObject(camera, Formatting.Indented), ex);

            return null;
        }
    }

    public async Task<Camera?> UpdateCameraAsync(ObjectId objectId, Camera camera)
    {
        var filter = Builders<Camera>.Filter.Eq("_id", objectId);
        var update = Builders<Camera>.Update
            .Set(c => c.Streams, camera.Streams)
            .Set(c => c.Name, camera.Name)
            .Set(c => c.Username, camera.Username)
            .Set(c => c.Password, camera.Password)
            .Set(c => c.Driver, camera.Driver)
            .Set(c => c.Ip, camera.Ip)
            .Set(c => c.Streams, camera.Streams)
            .Set(c => c.Ptz, camera.Ptz);
        return await Collection.FindOneAndUpdateAsync(filter, update,
            new FindOneAndUpdateOptions<Camera, Camera> { ReturnDocument = ReturnDocument.After });
    }

    public async Task<List<Camera>> GetSearchByNameCameras(string textToSearch)
    {
        if (string.IsNullOrWhiteSpace(textToSearch))
            return [];

        if (textToSearch.Length > 100)
            throw new BadRequestException("Search text too long");

        var safeInput = Regex.Escape(textToSearch);

        var filter = Builders<Camera>.Filter.Regex(
            c => c.Name,
            new BsonRegularExpression(safeInput, "i")
        );

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

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