using System.Diagnostics;
using System.Text;
using Exsersewo.Common.Extensions;
using Kynareth.Helpers;
using Kynareth.Models;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;
using StatsdClient;

namespace Kynareth.Attributes;

public class EndpointMetricsAttribute : ActionFilterAttribute
{
	public string EndpointMetricName;

	private Stopwatch watch = new Stopwatch();

	public EndpointMetricsAttribute(string metricName)
	{
		EndpointMetricName = metricName;
	}

	public override void OnActionExecuting(ActionExecutingContext context)
	{
		base.OnActionExecuting(context);

#if DEBUG
		Debug.WriteLine("Executing");
#endif

		watch.Restart();
		watch.Start();
	}

	public override void OnActionExecuted(ActionExecutedContext context)
	{
		base.OnActionExecuted(context);
		
		watch.Stop();
		
#if DEBUG
		Debug.WriteLine("Executed");
#endif

		string key = context.HttpContext.Request.GetToken();

		if (!string.IsNullOrWhiteSpace(key))
		{
			using var database = context.HttpContext.RequestServices.GetRequiredService<KynarethDbContext>();

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

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

				database.SaveChanges();
			}
		}

		string environment = new StringBuilder("environment:")
#if DEBUG
			.Append("dev")
#else
			.Append("production")
#endif
			.ToString();
		
		DogStatsd.Gauge(EndpointMetricName, watch.Elapsed.TotalSeconds, tags: new[] { environment });
		
		DogStatsd.Increment(EndpointMetricName, tags: new[] { environment });
	}
}