using Tiku.Application.Commerce;
using Tiku.Application.Security;
using Tiku.Application.Tenancy;
using Tiku.Domain.Commerce;
using Tiku.Domain.Tenancy;

namespace Tiku.Api.Controllers;

public sealed class CommerceRequestContextResolver(
    ICurrentUser currentUser,
    ITenantContext currentTenant,
    ITenantContextInitializer tenantInitializer,
    ITenantDirectory tenantDirectory)
{
    internal CommerceActor ResolveActor()
    {
        if (currentTenant.TenantId is null || currentUser.UserId is null)
            throw new CommerceException("Current commerce actor was not resolved.", "commerce_access_denied");

        return new CommerceActor(currentTenant.TenantId.Value, currentUser.UserId.Value);
    }

    internal async Task<Guid> ResolveNotificationTenantAsync(
        string? tenantCode,
        CancellationToken cancellationToken)
    {
        if (currentTenant.TenantId.HasValue) return currentTenant.TenantId.Value;

        if (string.IsNullOrWhiteSpace(tenantCode))
            throw new CommerceException("Tenant code is required for payment notification.", "tenant_required");

        var tenant = await tenantDirectory.FindByCodeAsync(tenantCode.Trim(), cancellationToken)
                     ?? throw new CommerceException("Tenant was not found.", "tenant_not_found");
        tenantInitializer.Initialize(tenant.TenantId, tenant.TenantCode, TenantResolutionSource.TenantCode);
        return tenant.TenantId;
    }
}
