using FluentResults;
using Result = FluentResults.Result;
using Microsoft.Maui.Storage;
using NexusReader.Application.Abstractions.Services;

namespace NexusReader.Maui.Services;

public sealed class MauiStorageService : INativeStorageService
{
    public Task<Result> SaveStringAsync(string key, string value)
    {
        try 
        {
            Preferences.Default.Set(key, value);
            return Task.FromResult(Result.Ok());
        }
        catch (Exception ex)
        {
            return Task.FromResult(Result.Fail(ex.Message));
        }
    }

    public Task<Result<string?>> GetStringAsync(string key)
    {
        try 
        {
            return Task.FromResult(Result.Ok(Preferences.Default.Get(key, (string?)null)));
        }
        catch (Exception ex)
        {
            return Task.FromResult(Result.Fail<string?>(ex.Message));
        }
    }

    public Task<Result> SaveBoolAsync(string key, bool value)
    {
        try 
        {
            Preferences.Default.Set(key, value);
            return Task.FromResult(Result.Ok());
        }
        catch (Exception ex)
        {
            return Task.FromResult(Result.Fail(ex.Message));
        }
    }

    public Task<Result<bool>> GetBoolAsync(string key, bool defaultValue = false)
    {
        try 
        {
            return Task.FromResult(Result.Ok(Preferences.Default.Get(key, defaultValue)));
        }
        catch (Exception ex)
        {
            return Task.FromResult(Result.Fail<bool>(ex.Message));
        }
    }

    public Task<Result> RemoveAsync(string key)
    {
        try 
        {
            Preferences.Default.Remove(key);
            return Task.FromResult(Result.Ok());
        }
        catch (Exception ex)
        {
            return Task.FromResult(Result.Fail(ex.Message));
        }
    }

    public async Task<Result> SaveSecureString(string key, string value)
    {
        try
        {
            await SecureStorage.Default.SetAsync(key, value);
            return Result.Ok();
        }
        catch (Exception ex)
        {
            return Result.Fail(ex.Message);
        }
    }

    public async Task<Result<string?>> GetSecureString(string key)
    {
        try
        {
            return Result.Ok(await SecureStorage.Default.GetAsync(key));
        }
        catch (Exception ex)
        {
            return Result.Fail(ex.Message);
        }
    }

    public Task<Result> RemoveSecureAsync(string key)
    {
        try
        {
            SecureStorage.Default.Remove(key);
            return Task.FromResult(Result.Ok());
        }
        catch (Exception ex)
        {
            return Task.FromResult(Result.Fail(ex.Message));
        }
    }
}
