summaryrefslogtreecommitdiff
path: root/Validations/MaximumWinners.cs
blob: 06a467af201169be5d975e33b48e52ee9e1ce4d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System.ComponentModel.DataAnnotations;
using BackendPIA.Models;

namespace BackendPIA.Validations {
    public class MaximumWinners : ValidationAttribute {
        public string GetMaximumWinnersMessage(object? value) {
          return $"The given raffle has reached the prize limit.";
        }

        public string GetNullRaffleErrorMessage(object? value) {
            return $"The raffle with id {value} doesn't exist";
        }

        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) {
            var db_context = (ApplicationDbContext) validationContext.GetService(typeof(ApplicationDbContext));
            var raffle = db_context.Raffles.Find((long) value);

            if(raffle == null)
                return new ValidationResult(GetNullRaffleErrorMessage(value));

            if(db_context.Prizes.Where(p => p.RaffleId == (long) value).Count() >= raffle.Winners) 
                return new ValidationResult(GetMaximumWinnersMessage(value));
            
            return ValidationResult.Success;
        }
    }
}