using System.Diagnostics;
using Microsoft.Extensions.Logging;

namespace Kbx.Shared.Runtime;

public static class KbxTelemetry
{
    public static readonly ActivitySource ActivitySource = new("KBX.BusinessRuntime");

    public static Activity? StartOperation(
        string operationName,
        KbxRequestContext context,
        string? entityType = null,
        string? entityId = null)
    {
        var activity = ActivitySource.StartActivity(operationName, ActivityKind.Internal);
        if (activity is null) return null;

        activity.SetTag("kbx.screen.id", context.ScreenId);
        activity.SetTag("kbx.correlation.id", context.CorrelationId);
        activity.SetTag("kbx.tenant.id", context.TenantId?.ToString());
        activity.SetTag("kbx.entity.type", entityType);
        activity.SetTag("kbx.entity.id", entityId);
        return activity;
    }

    public static void LogFailure(
        ILogger logger,
        Exception exception,
        KbxRequestContext context,
        string operation)
    {
        logger.LogError(exception,
            "KBX operation failed. Operation={Operation} ScreenId={ScreenId} CorrelationId={CorrelationId}",
            operation, context.ScreenId, context.CorrelationId);
    }
}
