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

export const Stores = new Mongo.Collection('stores');

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

Meteor.methods({
    'add.store' (storeName) {
        check(storeName, String);

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

        return Stores.insert({
            storeName: storeName,
            owner: this.userId,
        });
    },
    'edit.store' (storeId, storeName) {
        check(storeId, String);
        check(storeName, String);

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

        return Stores.update({ _id: storeId }, {
            $set: {
                storeName: storeName,
            }
        });
    },
    'delete.store' (storeId) {
        check(storeId, String);

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

        let storeInfo = Stores.findOne({ _id: storeId });
        let myId = this.userId;
        if (myId == storeInfo.owner) {
            return Stores.remove({ _id: storeId });
        } else {
            console.log("User not allowed to delete this store. Not the owner!");
            return("Not Allowed!");
        }
    },
});