using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using QuantEngine.Core.Interfaces;
using QuantEngine.Core.Models;

namespace QuantEngine.Application.Services
{
    public class ApprovalService
    {
        private readonly IWorkspaceRepository _repository;

    public ApprovalService(IWorkspaceRepository repository)
    {
        _repository = repository;
    }

    public Task<IEnumerable<WorkspaceApproval>> GetApprovalsAsync() => _repository.GetApprovalsAsync();
    public Task<WorkspaceApproval?> GetApprovalAsync(string domain, string targetRef)
        => _repository.GetApprovalAsync(RequireValue(domain, nameof(domain)), RequireValue(targetRef, nameof(targetRef)));
    public Task<bool> UpsertApprovalAsync(WorkspaceApproval approval)
    {
        ArgumentNullException.ThrowIfNull(approval);
        return _repository.UpsertApprovalAsync(approval);
    }

    public Task<IEnumerable<WorkspaceLock>> GetLocksAsync() => _repository.GetLocksAsync();
    public Task<WorkspaceLock?> GetLockAsync(string domain, string targetRef)
        => _repository.GetLockAsync(RequireValue(domain, nameof(domain)), RequireValue(targetRef, nameof(targetRef)));
    public Task<bool> AcquireLockAsync(WorkspaceLock @lock)
    {
        ArgumentNullException.ThrowIfNull(@lock);
        return _repository.AcquireLockAsync(@lock);
    }
    public Task<bool> ReleaseLockAsync(string domain, string targetRef)
        => _repository.ReleaseLockAsync(RequireValue(domain, nameof(domain)), RequireValue(targetRef, nameof(targetRef)));

    private static string RequireValue(string value, string parameterName)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new ArgumentException("Value is required.", parameterName);
        }

        return value.Trim();
    }
}
}
