// samples/service.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const mongoose = require('mongoose');

const Item = mongoose.model('Item');

const { SiteService } = require('../../lib/site-lib');

class SampleService extends SiteService {

  constructor (dtp) {
    super(dtp, module.exports);
  }

  async start ( ) {
    await super.start();

    this.queue = this.getJobQueue('sample', this.dtp.config.jobQueues.sample);
  }

  async stop ( ) {
    // do your shutdown here

    await super.stop();
  }

  async create (owner, itemDefinition) {
    const NOW = new Date();
    const item = new Item();

    item.created = NOW;
    item.title = itemDefinition.title;
    item.content = itemDefinition.content;

    await item.save();

    return item.toObject();
  }

  async getItems (search, pagination) {
    const items = await Item
      .find(search)
      .sort({ created: -1 })
      .skip(pagination.skip)
      .limit(pagination.cpp)
      .lean();
    return items;
  }

  async getById (itemId) {
    const item = await Item.findById(itemId).lean();
    return item;
  }

  async deleteItem (item) {
    await Item.deleteOne({ _id: item._id });
  }
}

module.exports = {
  name: 'sample',
  slug: 'sample',
  create: (dtp) => { return new SampleService(dtp); },
};