using Couchbase.Lite;
using Microsoft.Extensions.Options;
using WorkTracker.Configuration;

namespace WorkTracker.Services.Storage;

public sealed class CouchbaseLiteDatabaseProvider : IDisposable
{
    private const string AppSettingsCollectionName = "app_settings";
    private const string UsersCollectionName = "users";
    private const string WorkDaysCollectionName = "workdays";

    private readonly Database database;

    public CouchbaseLiteDatabaseProvider(IOptions<CouchbaseLiteOptions> options, IHostEnvironment environment)
    {
        var configuredOptions = options.Value;
        var databaseDirectory = ResolveDirectory(configuredOptions.Directory, environment.ContentRootPath);
        Directory.CreateDirectory(databaseDirectory);

        database = new Database(
            configuredOptions.DatabaseName,
            new DatabaseConfiguration
            {
                Directory = databaseDirectory
            });

        AppSettings = database.GetCollection(AppSettingsCollectionName) ?? database.CreateCollection(AppSettingsCollectionName);
        Users = database.GetCollection(UsersCollectionName) ?? database.CreateCollection(UsersCollectionName);
        WorkDays = database.GetCollection(WorkDaysCollectionName) ?? database.CreateCollection(WorkDaysCollectionName);
    }

    public Collection AppSettings { get; }

    public Collection Users { get; }

    public Collection WorkDays { get; }

    public void Dispose()
    {
        database.Close();
        database.Dispose();
    }

    private static string ResolveDirectory(string configuredDirectory, string contentRootPath)
    {
        if (string.IsNullOrWhiteSpace(configuredDirectory))
        {
            return Path.Combine(contentRootPath, "App_Data", "couchbase");
        }

        return Path.IsPathRooted(configuredDirectory)
            ? configuredDirectory
            : Path.GetFullPath(Path.Combine(contentRootPath, configuredDirectory));
    }
}