using System.Net;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Services;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace AutopilotMonitor.Functions.Functions.Metrics
{
///
/// Function for retrieving tenant-specific usage metrics (Tenant Admin)
///
public class UsageMetricsFunction
{
private readonly ILogger _logger;
private readonly UsageMetricsService _usageMetricsService;
public UsageMetricsFunction(
ILogger logger,
UsageMetricsService usageMetricsService)
{
_logger = logger;
_usageMetricsService = usageMetricsService;
}
///
/// GET /api/metrics/usage?tenantId={tenantId} - Compute and return tenant-specific usage metrics
/// On-demand computation with 5-minute cache (Tenant Admin)
///
[Function("GetTenantUsageMetrics")]
public async Task Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "metrics/usage")]
HttpRequestData req)
{
_logger.LogInformation("Tenant usage metrics requested");
try
{
// Authentication + MemberRead authorization enforced by PolicyEnforcementMiddleware
string tenantId = TenantHelper.GetTenantId(req);
string userIdentifier = TenantHelper.GetUserIdentifier(req);
_logger.LogInformation($"Fetching usage metrics for tenant {tenantId} by user {userIdentifier}");
var metrics = await _usageMetricsService.ComputeTenantUsageMetricsAsync(tenantId);
var response = req.CreateResponse(HttpStatusCode.OK);
await response.WriteAsJsonAsync(metrics);
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error computing tenant usage metrics");
var errorResponse = req.CreateResponse(HttpStatusCode.InternalServerError);
await errorResponse.WriteAsJsonAsync(new
{
success = false,
message = "Failed to compute tenant usage metrics"
});
return errorResponse;
}
}
}
}