public PurchaseViewModel(Purchase purchase)
 {
     Price = purchase.Price;
     DateOfPurchase = purchase.DateOfPurchase;
     IsRecalled = purchase.IsRecalled;
     Book = new BookViewModel(purchase.Book);
 }
        public IHttpActionResult CreatePurchase(int id)
        {
            var book = this.Data.Books.Find(id);
            var currentUserId = this.User.Identity.GetUserId();
            var user = this.Data.Users.First(u => u.Id == currentUserId);
            if (book == null)
            {
                return this.BadRequest("invalid book id");
            }

            var purchase = new Purchase()
            {
                Book = book,
                User = user,
                Price = book.Price,
                PurchaseDate = DateTime.Now,
                isRecalled = false
            };
            if (book.Copies == 0)
            {
                return this.BadRequest("no book copies left");
            }

            book.Copies = book.Copies - 1;
            this.Data.Purchases.Add(purchase);
            this.Data.SaveChanges();
            
            var result = new PurchaseViewModel()
            {
                Price = purchase.Price,
                PurchaseDate = purchase.PurchaseDate,
                IsRecalled = purchase.isRecalled,
                PurchasePrice = purchase.Price,
                BookTitle = purchase.Book.Title
            };
            return this.Ok(result);

        }
        public IHttpActionResult BuyBook([FromUri]int id)
        {
            var book = this.context.Books.FirstOrDefault(b => b.Id == id);

            if (book == null)
            {
                return this.NotFound();
            }

            var rnd = new Random();

            var purchase = new Purchase()
            {
                Book = book,
                BookId = book.Id,
                Date = DateTime.Now.AddDays(rnd.Next(-100, 0)),
                IsRecalled = false,
                Price = book.Price,
                User = this.context.Users.FirstOrDefault(u => u.UserName == this.User.Identity.Name)
            };

            book.Copies--;

            this.context.Purchases.Add(purchase);

            try
            {
                this.context.SaveChanges();

                return this.Ok("Book purchased successfully");
            }
            catch (Exception)
            {
                return this.BadRequest();
            }
        }