import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { check } from 'meteor/check';

export const Recipes = new Mongo.Collection('recipes');

Recipes.allow({
    insert: function(userId, doc){
        // if use id exists, allow insert
        return !!userId;
    },
});

Meteor.methods({
    'add.recipe' (recipeName) {
        check(recipeName, String);

        if (!this.userId) {
            throw new Meteor.Error('You are not allowed to add recipes. Make sure you are logged in with valid user credentials.');
        }

        return Recipes.insert({
            recipeName: recipeName,
            addedBy: this.userId,
            addedOn: new Date(),
        });
    },
    'edit.recipe' (recipeId, recipeName) {
        check(recipeId, String);
        check(recipeName, String);

        if (!this.userId) {
            throw new Meteor.Error('You are not allowed to add recipes. Make sure you are logged in with valid user credentials.');
        }

        return Recipes.update({ _id: recipeId }, {
            $set: {
                recipeName: recipeName,
                updatedOn: new Date(),
                updatedBy: this.userId,
            }
        });
    },
    'delete.recipe' (recipeId) {
        check(recipeId, String);

        if (!this.userId) {
            throw new Meteor.Error('You are not allowed to delete recipes. Make sure you are logged in with valid user credentials.');
        }

        return Recipes.remove({ _id: recipeId });
    }
});