using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;

namespace SkyArtShop.Services;

public class MongoDBService
{
	private readonly IMongoDatabase _database;

	private readonly MongoDBSettings _settings;

	public MongoDBService(IOptions<MongoDBSettings> settings)
	{
		_settings = settings.Value;
		MongoClientSettings mongoClientSettings = MongoClientSettings.FromConnectionString(_settings.ConnectionString);
		mongoClientSettings.MaxConnectionPoolSize = 500;
		mongoClientSettings.MinConnectionPoolSize = 50;
		mongoClientSettings.WaitQueueTimeout = TimeSpan.FromSeconds(30.0);
		mongoClientSettings.ServerSelectionTimeout = TimeSpan.FromSeconds(10.0);
		mongoClientSettings.ConnectTimeout = TimeSpan.FromSeconds(10.0);
		mongoClientSettings.SocketTimeout = TimeSpan.FromSeconds(60.0);
		MongoClient mongoClient = new MongoClient(mongoClientSettings);
		_database = mongoClient.GetDatabase(_settings.DatabaseName);
	}

	public IMongoCollection<T> GetCollection<T>(string collectionName)
	{
		return _database.GetCollection<T>(collectionName);
	}

	public async Task<List<T>> GetAllAsync<T>(string collectionName)
	{
		IMongoCollection<T> collection = GetCollection<T>(collectionName);
		return await collection.Find((T _) => true).ToListAsync();
	}

	public async Task<T> GetByIdAsync<T>(string collectionName, string id)
	{
		IMongoCollection<T> collection = GetCollection<T>(collectionName);
		FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", ObjectId.Parse(id));
		return await collection.Find(filter).FirstOrDefaultAsync();
	}

	public async Task InsertAsync<T>(string collectionName, T document)
	{
		IMongoCollection<T> collection = GetCollection<T>(collectionName);
		await collection.InsertOneAsync(document);
	}

	public async Task UpdateAsync<T>(string collectionName, string id, T document)
	{
		IMongoCollection<T> collection = GetCollection<T>(collectionName);
		FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", ObjectId.Parse(id));
		await collection.ReplaceOneAsync(filter, document);
	}

	public async Task DeleteAsync<T>(string collectionName, string id)
	{
		IMongoCollection<T> collection = GetCollection<T>(collectionName);
		FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", ObjectId.Parse(id));
		await collection.DeleteOneAsync(filter);
	}
}
