using adas_core.Application.Repositories.Interfaces;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using adas_core.Domain.Models.Responses;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;

namespace adas_core.Infrastructure.Repositories;

public class DisplayCardConfigRepository : MongoRepository<CardConfig>, IDisplayCardConfigRepository
{
    private readonly ApiSettings _apiSettings;
    private readonly ILogger<DisplayCardConfigRepository> _logger;
    

    public DisplayCardConfigRepository(
        IMongoDatabase database,
        ApiSettings apiSettings,
        ILogger<DisplayCardConfigRepository> logger
    ) : base(database)
    {
        _apiSettings = apiSettings;
        _logger = logger;
    }

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

    public async Task<List<CardConfig>> GetAll()
    {
        var result = await Collection.Find(Builders<CardConfig>.Filter.Empty).ToListAsync();
        return result;
    }

    public async Task<CardConfig?> GetById(ObjectId configId)
    {
        try
        {
            var result = await Collection.FindAsync(Builders<CardConfig>.Filter.Eq(p => p.Id, configId));
            return await result.FirstOrDefaultAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError("Error on config card display repository on GetById Exception: {ex}", ex.Message);
            return null;
        }
    }

    public async Task<CardConfig?> InsertOneAsyncAndReturn(CardConfig config)
    {
        try
        {
            await Collection.InsertOneAsync(config);
            return config;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex.Message);
            return null;
        }
    }

    public async Task<UpdateResponse<CardConfig?>> UpdateOne(CardConfig? config)
    {
        try
        {
            if (config == null) return new UpdateResponse<CardConfig?>(0, null);
            var filter = Builders<CardConfig>.Filter.Eq(c => c.Id, config.Id);
            var update = Builders<CardConfig>.Update.Set(c => c.Rows, config.Rows);

            var result = await Collection.UpdateOneAsync(filter, update);

            var updatedDoc = await Collection.Find(filter).FirstOrDefaultAsync();

            return new UpdateResponse<CardConfig?>(result.ModifiedCount, updatedDoc);
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message);
            return new UpdateResponse<CardConfig?>(0, null);
        }
    }

    public async Task<CardConfig?> DeleteOne(ObjectId configId)
    {
        return await DeleteAsync(configId);
    }

    public Task<object> UpdateCardConfigId(ObjectId? displayConfigId, ObjectId? resultId)
    {
        throw new NotImplementedException();
    }
}