using Exsersewo.Common.Extensions;
using Kynareth.Helpers;
using Kynareth.Models;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;

namespace Kynareth.Attributes;

public class EndpointMetricsAttribute : ActionFilterAttribute
{
	public string EndpointMetricName;

	public EndpointMetricsAttribute(string metricName)
	{
		EndpointMetricName = metricName;
	}
	
	public override void OnActionExecuted(ActionExecutedContext context)
	{
		base.OnActionExecuted(context);

		string key = context.HttpContext.Request.GetToken();
		
		if (string.IsNullOrWhiteSpace(key)) return;

		using var database = context.HttpContext.RequestServices.GetRequiredService<KynarethDbContext>();

		var token = database.Tokens.FirstOrDefault(x => x.Token.Equals(key));

		if (token is null) return;
		
		token.ApiCalls.Add(new() {
			TimeStamp = DateTime.UtcNow,
			Route = EndpointMetricName
		});

		database.SaveChanges();
	}
}