using MongoDB.Driver;

namespace YTExtractor.Data
{
    public class MongoDBConnector
    {
        private readonly IMongoDatabase _database;
        private readonly IMongoCollection<VideoData> _collection;

        public MongoDBConnector(IConfiguration configuration)
        {
            var connectionString = configuration.GetSection("MongoDbConnaction").Value;
            var client = new MongoClient(connectionString);
            _database = client.GetDatabase("YTExtractor");
            _collection = _database.GetCollection<VideoData>("videos");
        }

        public async Task InsertVideo(VideoData video)
        {
            await _collection.InsertOneAsync(video);
        }

        public async Task<VideoData> GetVideoById(string id)
        {
            return await _collection.Find(x => x.Id == id).FirstOrDefaultAsync();
        }

        public async Task<List<VideoData>> GetAllVideos()
        {
            return await _collection.Find(_ => true).ToListAsync();
        }

        public async Task UpdateVideo(VideoData video)
        {
            await _collection.ReplaceOneAsync(x => x.Id == video.Id, video);
        }

        public async Task DeleteVideo(string id)
        {
            await _collection.DeleteOneAsync(x => x.Id == id);
        }
        public async Task<VideoData> GetVideoByUrl(string url)
        {
            return await _collection.Find(x => x.Url == url).FirstOrDefaultAsync();
        }
    }
}
