namespace MyOffice.Web.Infrastructure.Attributes
{
	using System.ComponentModel.DataAnnotations;
	using Core.Extensions;

	public class AsGuidAttribute: ValidationAttribute
	{
		private readonly bool _nullable;

		public AsGuidAttribute(bool nullable = false)
		{
			_nullable = nullable;
		}

		protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
		{
			if (value == null && _nullable)
			{
				return ValidationResult.Success;
			}

			if (value == null || value.ToString().IsMissing())
			{
				return new ValidationResult("Id parameter is not valid");
			}

			if (!Guid.TryParse(value.ToString(), out _))
			{
				return new ValidationResult("Id parameter is not valid");
			}

			return ValidationResult.Success;
		}
	}
}
