using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace OnlineSalesAutoCrop.CoreAPI.Configurations
{
	/// <summary>
	/// Use to validate has any session  
	/// </summary>

	[AttributeUsage(AttributeTargets.Method)]
	public class ValidateSessionAttribute : ActionFilterAttribute
	{
		private static readonly string[] message = ["Your session has been expired, Please login again..."];

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="next"></param>
		/// <returns></returns>
		public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
		{
			ISession session = context.HttpContext.Session;
			if (session?.Keys == null || !session.Keys.Any())
			{
				context.Result = new ObjectResult(new
				{
					ReturnStatus = StatusCodesExt.StatusSessionExpired,
					ReturnMessage = message
				})
				{
					StatusCode = StatusCodesExt.StatusSessionExpired
				};
				return;
			}

			await next();
		}
	}
}