using System.Threading;
using System.Threading.Tasks;
using Knot.Contracts.Admin.Abstractions;
using Knot.Contracts.Klipy.Application.Abstractions;
using Knot.Contracts.Settings.Application.Abstractions;
using Knot.Contracts.Settings.Application.DTOs;
using MediatR;

namespace Knot.Modules.Admin.Application.Admin.Commands.TestKlipy;

public record TestKlipyConnectionCommand(string ApiKey, string AppName) : ICommand<bool>;

internal sealed class TestKlipyConnectionCommandHandler : ICommandHandler<TestKlipyConnectionCommand, bool>
{
    private readonly ISettingsService _settingsService;
    private readonly Knot.Contracts.Klipy.Application.Abstractions.IKlipyClient _klipyClient;

    public TestKlipyConnectionCommandHandler(ISettingsService settingsService, Knot.Contracts.Klipy.Application.Abstractions.IKlipyClient klipyClient)
    {
        _settingsService = settingsService;
        _klipyClient = klipyClient;
    }

    public async Task<Result<bool>> Handle(TestKlipyConnectionCommand request, CancellationToken ct)
    {
        if (string.IsNullOrEmpty(request.ApiKey))
        {
            return Result.Failure<bool>(new Error("Klipy.KeyMissing", "API Key for Klipy is not configured."));
        }

        var isOk = await _klipyClient.TestConnectionAsync(request.ApiKey, request.AppName, ct);
        if (!isOk)
        {
            return Result.Failure<bool>(new Error("Klipy.AuthFailed", "Klipy API test request failed. Verify your API key."));
        }

        return Result.Success(true);
    }
}


