const mongoose = require('mongoose');
const validator = require('validator');

const OrderSchema = new mongoose.Schema({
  coffee: [
    {
      name: {
        type: String,
        required: [true, 'Please provide a name.'],
      },
      customID: {
        type: String,
        required: [true, 'Please provide a custom id.'],
      },
    },
  ],
  time: {
    type: Date,
    required: [true, 'Please provide a date.'],
    validate(value) {
      if (!validator.isDate(value)) {
        throw new Error('Not a date');
      }
    },
  },
  totalPrice: {
    type: Number,
    required: [true, 'Please provide a total price.'],
    validate(value) {
      if (value < 0) {
        throw new Error('Total price must be a postive number');
      }
    },
  },
  numberOfItems: {
    type: Number,
    required: [true, 'Please provide a total number of items.'],
    validate(value) {
      if (value < 0) {
        throw new Error('Number of items must be a postive number');
      }
    },
  },
  fulfilled: {
    type: Boolean,
    default: false,
  },
  owner: {
    type: mongoose.Schema.Types.ObjectId,
    required: [true, 'Please provide an owner.'],
    ref: 'User',
  },
  stripeCheckoutId: {
    type: String,
    required: [true, 'Please provide a stripe checkout id.'],
    unique: [true, 'Stripe checkout id id must be unique.'],
  },
});

const Order = mongoose.models.Order || mongoose.model('Order', OrderSchema);

module.exports = Order;
