using Monitoring.Core.Domain.EventManagement;
using Monitoring.Core.Domain.UserPrimitives;

namespace Monitoring.Features.AlarmManagement;

public static class AlarmScopeStatusIQueryableExtensions
{
	private static readonly AlarmScopeStatus[] CommonOperatorStatuses = [AlarmScopeStatus.New];
	private static readonly AlarmScopeStatus[] OnlyThisOperatorStatuses =
	[
		AlarmScopeStatus.Accepted,
		AlarmScopeStatus.CamerasViewed,
		AlarmScopeStatus.CallsCompleted,
		AlarmScopeStatus.CommentAndSend,
	];

	public static IQueryable<Alarm> GetAllowed(this IQueryable<Alarm> query, UserId userId)
	{
		return query.Where(x =>
			CommonOperatorStatuses.Contains(
				x.Scope.StatusHistory.OrderByDescending(s => s.CreatedAt).First().Status
			)
			|| (
				OnlyThisOperatorStatuses.Contains(
					x.Scope.StatusHistory.OrderByDescending(s => s.CreatedAt).First().Status
				)
				&& x.Scope.StatusHistory.OrderByDescending(s => s.CreatedAt).First().UserId
					== userId
			)
		);
	}

	public static IQueryable<AlarmScope> GetAllowed(
		this IQueryable<AlarmScope> query,
		UserId userId
	)
	{
		return query.Where(x =>
			CommonOperatorStatuses.Contains(
				x.StatusHistory.OrderByDescending(s => s.CreatedAt).First().Status
			)
			|| (
				OnlyThisOperatorStatuses.Contains(
					x.StatusHistory.OrderByDescending(s => s.CreatedAt).First().Status
				)
				&& x.StatusHistory.OrderByDescending(s => s.CreatedAt).First().UserId == userId
			)
		);
	}
}
