const data = require("../../db.js");
let cats = [
  {"id":1,"title":"Продукты","description":null,"hidden":false,"type":1,"items":[]},
  {"id":2,"title":"Стандарты","description":null,"hidden":false,"type":2,"items":[]},
  {"id":3,"title":"Категории","description":null,"hidden":false,"type":2,"items":[]},
  {"id":4,"title":"4й блок","description":null,"hidden":false,"type":2,"items":[]}];

module.exports = {
  '/api/new': {
    options: {},
    method: 'GET',
    summary: 'Get list of new cards',
    fn: async function(args) {
      return Object.values(data.products);
    }
  },
  '/api/card_info/:categoryID/:cardID': {
    method: 'GET',
    summary: 'Get card details',
    options: {
      categoryID: { required: true, description: 'ID of card category', type: Number },
      cardID: { required: true, description: 'ID of card in category', type: Number }
    },
    fn: async function( args ){
      let searched = Object.values( data.products ).filter( p => p.id === args.cardID && p.category_id === args.categoryID );
      if( searched.length ){
        return searched[ 0 ];
      }else{
        throw new Error( 'No matched product' )
      }
    }
  },
  '/api/categories': {
    method: 'GET',
    summary: 'Get list of all categories',
    options: {},
    fn: async function(args) {
      return cats.map(c=>{
          c.count = Object.values(data.products).filter(p=>p.category_id+'' === c.id+'').length;
          return c;
      });
    }
  },
  '/api/categories/:id': {
    method: 'GET',
    summary: 'Fetch category data with child cards',
    options: {
      id: {required: true, description: 'ID of Category to fetch', type: Number}
    },
    fn: async function(args) {
      return Object.assign({}, cats.filter(c=>c.id+''===args.id+'')[0], {
        items:Object.values(data.products).filter(p=>p.category_id+'' === args.id+'')
      });
    }
  },
  '/api/hang': {
    method: 'GET',
    summary: 'Fetch category data with child cards',
    options: {},
    fn: async function(args) {
      return await new Promise(()=>{});
    }
  }
};