using adas_core.Application.Repositories.Interfaces;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.DTO;
using adas_core.Domain.Models.MongoModels;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoUtils = adas_core.Infrastructure.Utils.MongoUtils;

namespace adas_core.Infrastructure.Repositories;

public class DeviceRepository : MongoRepository<Device>, IDeviceRepository
{
    private readonly ApiSettings _apiSettings;

    public DeviceRepository(ApiSettings apiSettings, IMongoDatabase database) : base(database)
    {
        _apiSettings = apiSettings;
    }

    public override string GetCollectionName()
    {
        return _apiSettings.Devices ?? "devices";
    }
    
    public override async Task CreateIndexes()
    {
        var options = new CreateIndexOptions { Background = true, Unique = true };
        var indexes = new List<CreateIndexModel<Device>>
        {
            new(Builders<Device>.IndexKeys.Ascending(d => d.MacAddr), options),
            new(Builders<Device>.IndexKeys.Ascending(d => d.SerialNumber), new CreateIndexOptions { Background = true }),
            new(Builders<Device>.IndexKeys.Ascending(d => d.Uuid), new CreateIndexOptions { Background = true }),
            new(Builders<Device>.IndexKeys.Ascending(d => d.Key), new CreateIndexOptions { Background = true })
        };

        await MongoUtils.EnsureIndexes(Collection, indexes);
    }

    public async Task<Device?> FindByMacAddr(string deviceDtoMacAddr)
    {
        return await Collection
            .Find(d => d.MacAddr == deviceDtoMacAddr)
            .FirstOrDefaultAsync();
    }

    public async Task<Device?> FindBySerialNumber(string deviceDtoSerialNumber)
    {
        return await Collection
            .Find(d => d.SerialNumber == deviceDtoSerialNumber)
            .FirstOrDefaultAsync();
    }

    public async Task<Device?> FindByUuid(string deviceDtoUuid)
    {
        return await Collection
            .Find(d => d.Uuid == deviceDtoUuid)
            .FirstOrDefaultAsync();
    }

    public async Task<Device?> FindByKey(string deviceDtoKey)
    {
        return await Collection
            .Find(d => d.Key == deviceDtoKey)
            .FirstOrDefaultAsync();
    }

    public async Task UpdateDeviceStats(ObjectId id, DeviceDto deviceExist)
    {
        var update = Builders<Device>.Update
            .Set(d => d.Battery, deviceExist.Battery)
            .Set(d => d.Connected, deviceExist.Connected)
            .Set(d => d.Ready, deviceExist.Ready)
            .Set(d => d.Name, deviceExist.Name)
            .Set(d => d.UpdatedAt, DateTime.UtcNow);

        await Collection.UpdateOneAsync(
            d => d.Id == id, 
            update
        );
    }
}