using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;

using WeatherForecast.Models.Abstractions;
using Core.DomainObjects.Documents;
using Core.Enumerations;
using Extensions;


namespace WeatherForecast.Models.Requests {

  /// <summary>
  /// 
  /// </summary>
  public class ShopItemRequestModel : PostItemRequestModelBase<ShopItem> {

    /// <summary>
    /// 
    /// </summary>
    public string? BrandName { get; set; }

    /// <summary>
    /// 
    /// </summary>
    public decimal? Rating { get; set; }

    /// <summary>
    /// 
    /// </summary>
    public decimal? Price { get; set; }

    /// <summary>
    /// 
    /// </summary>
    public decimal? NewPrice { get; set; }

    /// <summary>
    /// 
    /// </summary>
    public uint? Quantity { get; set; }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public override ShopItem ToDomainObject() {
      if (HasValidationErrors(this) || HasValidationErrorsBase(HasValidationErrors(this)))
        throw new ValidationException();
    
      return new ShopItem() {
        L10n = L10n.Select(x => x.ToDomainObject()).ToList(),
        MediaAttachments = MediaAttachments?.Select(x => x.ToDomainObject()).ToList(),
        // Author
        Created = DateTime.UtcNow,
        Tags = Tags,
        FamilyFriendly = FamilyFriendly,

        BrandName = BrandName,
        Rating = Rating,
        Price = Price.Value,
        NewPrice = NewPrice,
        Quantity = Quantity.Value
      };
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="validationContext"></param>
    /// <returns></returns>
    public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
      if (L10n.IsNullOrEmpty())
        yield return new ValidationResult($"{nameof(L10n)} {Errors.NullOrEmpty}");

      if (MediaAttachments.IsNullOrEmpty())
        yield return new ValidationResult($"{nameof(MediaAttachments)} {Errors.NullOrEmpty}");

      if (string.IsNullOrWhiteSpace(BrandName))
        yield return new ValidationResult($"{nameof(BrandName)} {Errors.NullOrWhiteSpace}");

      if (Price == null || (Price != null && Price == 0))
        yield return new ValidationResult($"{nameof(Price)} {Errors.NullOrEmpty.Name}");

      if (Quantity == null || (Quantity != null && Quantity == 0))
        yield return new ValidationResult($"{nameof(Quantity)} {Errors.NullOrEmpty}");
    }

    [MemberNotNullWhen(false, new[] { nameof(BrandName), nameof(Price), nameof(Quantity) })]
    private bool HasValidationErrors(ShopItemRequestModel model) => Validate(new ValidationContext(model)).Any();
  }
}
