import { Meteor } from 'meteor/meteor';
import { LinksCollection } from '/imports/api/links';

async function insertLink({ title, url }) {
  await LinksCollection.insertAsync({ title, url, createdAt: new Date() });
}

Meteor.startup(async () => {
  // If the Links collection is empty, add some data.
  if (await LinksCollection.find().countAsync() === 0) {
    await insertLink({
      title: 'Do the Tutorial',
      url: 'https://angular.io/tutorial',
    });

    await insertLink({
      title: 'Follow the Guide',
      url: 'https://angular.io/guide/architecture',
    });

    await insertLink({
      title: 'Read the Docs',
      url: 'https://angular.io/docs',
    });

    await insertLink({
      title: 'Join the Community',
      url: 'https://angular.io/community',
    });
  }

  // We publish the entire Links collection to all clients.
  // In order to be fetched in real-time to the clients
  Meteor.publish("links", function () {
    return LinksCollection.find();
  });
});
