using System.Net;
using Exsersewo.Common.Utilities;
using Kynareth.Helpers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Kynareth.Attributes;

[AttributeUsage(AttributeTargets.Class)]
public class RequireTokenAttribute : ActionFilterAttribute
{
	public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
	{
		if (await RequestHelper.IsRequestAuthenticatedAsync(context.HttpContext.Request))
		{
			await next();
			return;
		}

		context.HttpContext.Response.ContentType = "application/json";
		context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;

		var invalidRequest = EventResult.FromFailure("Unauthorized request");
		await context.HttpContext.Response.WriteAsync(invalidRequest.ToJson());
		return;
	}
}