using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;

namespace Monitoring.Services;

public class FileService
{
	private readonly IMongoDatabase _database;
	private readonly GridFSBucket _gridFsBucket;

	public FileService(string connectionString, string databaseName)
	{
		MongoClient client = new(connectionString);
		_database = client.GetDatabase(databaseName);
		_gridFsBucket = new GridFSBucket(_database);
	}

	public async Task<byte[]> GetFileById(ObjectId id)
	{
		return await _gridFsBucket.DownloadAsBytesAsync(id);
	}

	public async Task<string> Create(string filename, byte[] bytes, CancellationToken cancellationToken)
	{
		var id = await _gridFsBucket.UploadFromBytesAsync(filename, bytes, cancellationToken: cancellationToken);
		return id.ToString();
	}

	public Task Delete(string path, CancellationToken cancellationToken)
	{
		return _gridFsBucket.DeleteAsync(new ObjectId(path), cancellationToken);
	}

	public async Task<string> Update(string path, string filename, byte[] bytes, CancellationToken cancellationToken)
	{
		await Delete(path, cancellationToken);
		return await Create(filename, bytes, cancellationToken);
	}
}