export const blog = [
    {
        id: "blogAll",
        name: "Blog All",
        description: "Endpoint for retrieving all blog posts",
        method: "GET",
        route: "/v3/api/custom/lambda/blog/all",
        inputs: [
          {
            name: "limit",
            type: "query",
            rules: "",
            dataType: "Integer"
          },
          {
            name: "offset",
            type: "query",
            rules: "",
            dataType: "Integer"
          }
        ],
        response: [
          {
            id: "error",
            key: "error",
            value: "false",
            valueType: "Boolean",
            parent: ""
          },
          {
            id: "data",
            key: "data",
            value: "",
            valueType: "Array",
            parent: ""
          },
          {
            id: "limit",
            key: "limit",
            value: "",
            valueType: "Integer",
            parent: ""
          },
          {
            id: "offset",
            key: "offset",
            value: "",
            valueType: "Integer",
            parent: ""
          },
          {
            id: "count",
            key: "count",
            value: "",
            valueType: "Integer",
            parent: ""
          }
        ],
        code: "",
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      }, 
      {
        id: "blogSimilar",
        name: "Blog Similar",
        description: "Endpoint for retrieving similar blog posts",
        method: "GET",
        route: "/v3/api/custom/lambda/blog/similar/:id",
        inputs: [
          {
            name: "top",
            type: "query",
            rules: "",
            dataType: "Integer"
          }
        ],
        response: [
          {
            id: "error",
            key: "error",
            value: "false",
            valueType: "Boolean",
            parent: ""
          },
          {
            id: "data",
            key: "data",
            value: "",
            valueType: "Array",
            parent: ""
          }
        ],
        code: `

            
            app.get("/v3/api/custom/lambda/blog/all", publicMiddlewares, async function (req, res) {
                try {

                let sdk = req.sdk; 
                sdk.getDatabase();
                sdk.setProjectId(req.projectId);
                sdk.setTable('blog_post')
                let blogs = await sdk.get({})




                let limit = parseInt(req.query.limit) ? parseInt(req.query.limit) : 10 ;
                let offset = parseInt(req.query.offset) ? parseInt(req.query.offset) :  0;


                
                blogs = await includeTagsAndCategories(blogs, sdk);

                return res.status(200).json({ error: false, data: blogs.slice(offset * limit, offset * limit + limit), limit, offset, count: blogs.length});
                } catch (err) {
                console.error(err);
                res.status(404);
                res.json({
                    error: true,
                    message: err.message,
                });
                }
            });

        
        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogFilter",
        name: "Blog Filter",
        description: "Endpoint for filtering blog posts",
        method: "GET",
        route: "/v3/api/custom/lambda/blog/filter",
        inputs: [
          {
            name: "categories",
            type: "query",
            rules: "",
            dataType: "Array"
          },
          {
            name: "tags",
            type: "query",
            rules: "",
            dataType: "Array"
          },
          {
            name: "rule",
            type: "query",
            rules: "",
            dataType: "String"
          },
          {
            name: "search",
            type: "query",
            rules: "",
            dataType: "String"
          },
          {
            name: "limit",
            type: "query",
            rules: "",
            dataType: "Integer"
          },
          {
            name: "page",
            type: "query",
            rules: "",
            dataType: "Integer"
          }
        ],
        response: [
          {
            id: "error",
            key: "error",
            value: "false",
            valueType: "Boolean",
            parent: ""
          },
          {
            id: "data",
            key: "data",
            value: "",
            valueType: "Array",
            parent: ""
          }
        ],
        code: `

        app.get("/v3/api/custom/lambda/blog/filter", publicMiddlewares, async function (req, res) {
            try {
        
              let sdk = req.sdk; 
              sdk.getDatabase();
              sdk.setProjectId(req.projectId);
        
              let {categories, tags, rule, search} = req.query;
        
              let limit = parseInt(req.query.limit) ? parseInt(req.query.limit) : 10 ;
              let page = parseInt(req.query.page) ? parseInt(req.query.page) :  1;
              let offset = (page - 1) * limit;
        
              if(!categories) categories = []
              else categories = JSON.parse(categories);
        
              if(!tags) tags = []
              else tags = JSON.parse(tags)
              if(!search) search = ''
        
              let post_map = {} 
              sdk.setTable('blog_post')
              let blogs = await sdk.get({})
              let posts = [];
        
              if(rule== 'and'){
        
                for(let x of blogs){
                  let include = true;
                  if(!x.title.includes(search)) include = false;
                  sdk.setTable('blog_post_tags');
                  for(let y of tags){
                    let exist = await sdk.get({
                      post_id: x.id,
                      tag_id: y
                    })
        
                    if(exist.length==0) include = false;
                  }
        
                  sdk.setTable('blog_post_category');
                  for(let y of categories){
                    let exist = await sdk.get({
                      post_id: x.id,
                      category_id: y
                    })
        
                    if(exist.length==0) include = false;
                  }
        
                  if(include) posts.push(x);
                  
                }
        
              }
              else{
                for(let x of blogs){
                  let include = false;
                  // console.log(search, x.title);
                  if(x.title.includes(search) && search) include = true;
                  sdk.setTable('blog_post_tags');
                  for(let y of tags){
                    let exist = await sdk.get({
                      post_id: x.id,
                      tag_id: y
                    })
        
                    if(exist.length!=0) include = true;
                  }
        
                  sdk.setTable('blog_post_category');
                  for(let y of categories){
                    let exist = await sdk.get({
                      post_id: x.id,
                      category_id: y
                    })
        
                    if(exist.length!=0) include = true;
                  }
                  // console.log(include)
                  if(include) posts.push(x);
        
                }
              }
              if(tags.length==0 && categories.length==0 && search.length==0) posts = blogs;
        
              posts = await includeTagsAndCategories(posts, sdk)
              
        
              return res.status(200).json({ error: false, data: posts.slice(offset, offset+ limit) ,limit, page, total: posts.length, num_pages: ((posts.length + limit-1)/limit).toFixed(0)});
            } catch (err) {
              console.error(err);
              res.status(404);
              res.json({
                error: true,
                message: err.message,
              });
            }
          });
        
        
        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogCreate",
        name: "Blog Create",
        description: "Endpoint for creating a new blog post",
        method: "POST",
        route: "/v3/api/custom/lambda/blog/create",
        inputs: [
          { name: "title", type: "body", rules: "", dataType: "String" },
          { name: "body", type: "body", rules: "", dataType: "String" },
          { name: "meta", type: "body", rules: "", dataType: "Object" },
          { name: "tags", type: "body", rules: "", dataType: "Array" },
          { name: "categories", type: "body", rules: "", dataType: "Array" },
          { name: "content", type: "body", rules: "", dataType: "String" },
          { name: "description", type: "body", rules: "", dataType: "String" },
          { name: "thumbnail", type: "body", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: "false", valueType: "Boolean", parent: "" },
          { id: "data", key: "data", value: "Blog Created.", valueType: "String", parent: "" }
        ],
        code: `

        app.post("/v3/api/custom/lambda/blog/create", middlewares, async function (req, res) {
            try {
        
              let sdk = req.sdk; 
              sdk.getDatabase();
              sdk.setProjectId(req.projectId);
              
              let author = req.user_id;
              let {title, body, meta, tags, categories, content, description, thumbnail} = req.body;
              sdk.setTable('blog_tags');
              for(let x of tags){
  
                      let exist = await sdk.get({id: x})
  
                      if(exist.length == 0) throw new Error("Tag doesn't Exist");
              }
  
              sdk.setTable('blog_category');
              for(let x of categories){
                      let exist = await sdk.get({id: x})
                      if(exist.length == 0) throw new Error("Category doesn't Exist");
              }
  
              sdk.setTable('user');
              let user = await sdk.get({id: author});
  
              meta = {
                 site_title: meta?.site_title ?? "",
                 domain : meta?.domain ?? "",
                 description: meta?.description ?? description,
                 site_name: meta?.site_name ?? req.projectId,
                 fbid: meta?.fbid ?? "",
                 author: user.first_name + " " + user.last_name,
                 twitter_handle: meta?.twitter_handle ?? ""
              }
  
              sdk.setTable('blog_post')
  
              let blog_id = await sdk.insert({
                      title, 
                      description,
                      content,
                      thumbnail,
                      author,
                      meta: JSON.stringify(meta),
                      create_at: sqlDateFormat(new Date()),
                      update_at: sqlDateTimeFormat(new Date())
  
              })
  
              sdk.setTable('blog_post_tags');
              for(let x of tags){
                      await sdk.insert({
                                post_id: blog_id,
                                tag_id: x,
                                create_at: sqlDateFormat(new Date()),
                                update_at: sqlDateTimeFormat(new Date())
                      })
              }
  
              sdk.setTable('blog_post_category');
              for(let x of categories){
                      await sdk.insert({
                                post_id: blog_id,
                                category_id: x,
                                create_at: sqlDateFormat(new Date()),
                                update_at: sqlDateTimeFormat(new Date())
                      })
              }
        
              return res.status(200).json({ error: false, data: "Blog Created." });
            } catch (err) {
              console.error(err);
              res.status(404);
              res.json({
                error: true,
                message: err.message,
              });
            }
          });
  
        
        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogEdit",
        name: "Blog Edit",
        description: "Endpoint for editing an existing blog post",
        method: "POST",
        route: "/v3/api/custom/lambda/blog/edit/:id",
        inputs: [
          { name: "id", type: "path", rules: "", dataType: "String" },
          { name: "title", type: "body", rules: "", dataType: "String" },
          { name: "content", type: "body", rules: "", dataType: "String" },
          { name: "description", type: "body", rules: "", dataType: "String" },
          { name: "meta", type: "body", rules: "", dataType: "Object" },
          { name: "tags", type: "body", rules: "", dataType: "Array" },
          { name: "categories", type: "body", rules: "", dataType: "Array" },
          { name: "thumbnail", type: "body", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: "false", valueType: "Boolean", parent: "" },
          { id: "data", key: "data", value: "Blog Edited.", valueType: "String", parent: "" }
        ],
        code: `
            
        app.post("/v3/api/custom/lambda/blog/edit/:id", middlewares, async function (req, res) {
            try {
        
              let sdk = req.sdk; 
              sdk.getDatabase();
              sdk.setProjectId(req.projectId);
  
              sdk.setTable('blog_post')
  
              let exist = await sdk.get({id: req.params.id});
  
              if(exist.length == 0) throw new Error("Blog doesn't exist");
              if(exist[0].author != req.user_id) throw new Error("Unauthorized");
  
  
              
              
              let {title, content, description, meta, tags, categories, thumbnail} = req.body;
              sdk.setTable('blog_tags');
              for(let x of tags){
  
                      let exist = await sdk.get({id: x})
  
                      if(exist.length == 0) throw new Error("Tag doesn't Exist");
              }
  
              sdk.setTable('blog_category');
              for(let x of categories){
                      let exist = await sdk.get({id: x})
                      if(exist.length == 0) throw new Error("Category doesn't Exist");
              }
  
              sdk.setTable('user');
              let user = await sdk.get({id: req.user_id});
  
              meta = {
                 site_title: meta?.site_title ?? "",
                 domain : meta?.domain ?? "",
                 description: meta?.description ?? description,
                 site_name: meta?.site_name ?? req.projectId,
                 fbid: meta?.fbid ?? "",
                 author: user.first_name + " " + user.last_name,
                 twitter_handle: meta?.twitter_handle ?? ""
              }
  
              sdk.setTable('blog_post')
  
              let blog_id = await sdk.update({
                      title, 
                      content,
                      description,
                      thumbnail,
                      meta: JSON.stringify(meta),
                      update_at: sqlDateTimeFormat(new Date())
  
              }, req.params.id)
  
              blog_id = req.params.id;
  
              sdk.setTable('blog_post_tags');
  
              await sdk.deleteWhere({post_id: req.params.id});
  
              for(let x of tags){
                      await sdk.insert({
                                post_id: blog_id,
                                tag_id: x,
                                create_at: sqlDateFormat(new Date()),
                                update_at: sqlDateTimeFormat(new Date())
                      })
              }
  
              sdk.setTable('blog_post_category');
  
              await sdk.deleteWhere({post_id: req.params.id});
  
              for(let x of categories){
                      await sdk.insert({
                                post_id: blog_id,
                                category_id: x,
                                create_at: sqlDateFormat(new Date()),
                                update_at: sqlDateTimeFormat(new Date())
                      })
              }
        
              return res.status(200).json({ error: false, data: "Blog Edited." });
            } catch (err) {
              console.error(err);
              res.status(404);
              res.json({
                error: true,
                message: err.message,
              });
            }
          });
        
        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogDelete",
        name: "Blog Delete",
        description: "Endpoint for deleting an existing blog post",
        method: "DELETE",
        route: "/v3/api/custom/lambda/blog/delete/:id",
        inputs: [
          { name: "id", type: "path", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: "false", valueType: "Boolean", parent: "" },
          { id: "data", key: "data", value: "Blog Deleted.", valueType: "String", parent: "" }
        ],
        code: `

            
        app.delete("/v3/api/custom/lambda/blog/delete/:id", middlewares, async function (req, res) {
            try {
        
              let sdk = req.sdk; 
              sdk.getDatabase();
              sdk.setProjectId(req.projectId);
  
              sdk.setTable('blog_post')
  
              let exist = await sdk.get({id: req.params.id});
  
              if(exist.length == 0) throw new Error("Blog doesn't exist");
              if(exist[0].author != req.user_id && req.role != 'admin') throw new Error("Unauthorized");
  
  
              sdk.setTable('blog_post_tags');
              await sdk.deleteWhere({
                post_id: exist[0].id
              })
             
              sdk.setTable('blog_post_category');
              await sdk.deleteWhere({
                post_id: exist[0].id
              })
              sdk.setTable('blog_post')
              sdk.deleteWhere({id: req.params.id})
        
              return res.status(200).json({ error: false, data: "Blog Deleted." });
            } catch (err) {
              console.error(err);
              res.status(404);
              res.json({
                error: true,
                message: err.message,
              });
            }
          });
        
        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogSingle",
        name: "Blog Single",
        description: "Endpoint for retrieving a single blog post",
        method: "GET",
        route: "/v3/api/custom/lambda/blog/single/:id",
        inputs: [
          { name: "id", type: "path", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: "false", valueType: "Boolean", parent: "" },
          { id: "data", key: "data", value: "", valueType: "Object", parent: "" },
          { id: "data_id", key: "id", value: "", valueType: "String", parent: "data" },
          { id: "data_title", key: "title", value: "", valueType: "String", parent: "data" },
          { id: "data_description", key: "description", value: "", valueType: "String", parent: "data" },
          { id: "data_content", key: "content", value: "", valueType: "String", parent: "data" },
          { id: "data_thumbnail", key: "thumbnail", value: "", valueType: "String", parent: "data" },
          { id: "data_author", key: "author", value: "", valueType: "String", parent: "data" },
          { id: "data_meta", key: "meta", value: "", valueType: "String", parent: "data" },
          { id: "data_create_at", key: "create_at", value: "", valueType: "String", parent: "data" },
          { id: "data_update_at", key: "update_at", value: "", valueType: "String", parent: "data" },
          { id: "data_tags", key: "tags", value: "", valueType: "Array", parent: "data" },
          { id: "data_tags_name", key: "name", value: "", valueType: "String", parent: "data_tags" },
          { id: "data_tags_id", key: "id", value: "", valueType: "String", parent: "data_tags" },
          { id: "data_categories", key: "categories", value: "", valueType: "Array", parent: "data" },
          { id: "data_categories_name", key: "name", value: "", valueType: "String", parent: "data_categories" },
          { id: "data_categories_id", key: "id", value: "", valueType: "String", parent: "data_categories" },
          { id: "data_views", key: "views", value: 0, valueType: "Number", parent: "data" }
        ],
        code: `

        app.get("/v3/api/custom/lambda/blog/single/:id", publicMiddlewares, async function (req, res) {
            try {
        
              let sdk = req.sdk; 
              sdk.getDatabase();
              sdk.setProjectId(req.projectId);
              sdk.setTable('blog_post');
              
              let blog_id = req.params.id;
  
              let blog = await sdk.get({
                 id: blog_id 
              });
  
              if(blog.length == 0) throw new Error("Blog Doesn't Exist");
  
              blog = blog[0];
  
              let tags = await sdk.join('blog_post_tags', 'blog_tags', 'tag_id', 'id', 'name, blog_tags.id', {post_id: blog.id});
              let categories = await sdk.join('blog_post_category', 'blog_category', 'category_id', 'id', 'name, blog_category.id', {post_id: blog.id});
  
              sdk.setTable('blog_post_views');
              let views = await sdk.get({post_id: blog.id })
              // console.log(req.ip);
              await sdk.insert({
                  post_id: blog.id,
                  viewer_ip: req.ip,
                 create_at: sqlDateFormat(new Date()),
                 update_at: sqlDateTimeFormat(new Date())
              })
        
              return res.status(200).json({ error: false, data: {
                      ...blog,
                      tags,
                      categories,
                      views : views.length
              } });
            } catch (err) {
              console.error(err);
              res.status(404);
              res.json({
                error: true,
                message: err.message,
              });
            }
          });
        
        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogTags",
        name: "Blog Tags",
        description: "Endpoint for retrieving a blog tag or creating if it does not exist ",
        method: "POST",
        route: "/v3/api/custom/lambda/blog/tags",
        inputs: [
          { name: "name", type: "body", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: "false", valueType: "Boolean", parent: "" },
          { id: "tag_id", key: "tag_id", value: "", valueType: "String", parent: "" }
        ],
        code: `
            
            app.post("/v3/api/custom/lambda/blog/tags", publicMiddlewares, async function (req, res) {
                try {

                let sdk = req.sdk; 
                sdk.getDatabase();
                sdk.setProjectId(req.projectId);
                sdk.setTable('blog_tags')

                let {name} = req.body;

                name = name.trim();
                name = name.toLowerCase();


                let r = await sdk.get({
                    name
                })


                if(r.length == 0){
                
                    r = await sdk.insert({
                    name,
                    create_at: sqlDateFormat(new Date()),
                    update_at: sqlDateTimeFormat(new Date())
                })

                }
                else{
                    r= r[0].id;
                }
                
                

                return res.status(200).json({ error: false, tag_id: r });
                } catch (err) {
                console.error(err);
                res.status(404);
                res.json({
                    error: true,
                    message: err.message,
                });
                }
            });

        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogTagsUpdate",
        name: "Blog Tags Update",
        description: "Endpoint for updating a blog tag by ID",
        method: "POST",
        route: "/v3/api/custom/lambda/blog/tags/:id",
        inputs: [
          { name: "name", type: "body", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: "false", valueType: "Boolean", parent: "" },
          { id: "message", key: "message", value: "Updated!", valueType: "String", parent: "" }
        ],
        code: `
            app.post("/v3/api/custom/lambda/blog/tags/:id", publicMiddlewares, async function (req, res) {
                try {
            
                let sdk = req.sdk; 
                sdk.getDatabase();
                sdk.setProjectId(req.projectId);
                sdk.setTable('blog_tags')
        
                let {name} = req.body;
        
                name = name.trim();
                name = name.toLowerCase();
        
        
                let r = await sdk.get({
                    name
                })
        
        
        
                if(r.length == 0 || r[0].id == req.params.id){
                
                    await sdk.updateWhere({
                    name,
                    update_at: sqlDateTimeFormat(new Date())
                }, {id: req.params.id})
        
                }
                else{
                throw new Error("Tag with this name alread exists!")
                }
                
            
                return res.status(200).json({ error: false, message: "Updated!" });
                } catch (err) {
                console.error(err);
                res.status(404);
                res.json({
                    error: true,
                    message: err.message,
                });
                }
        });
        
        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogTagsRetrieve",
        name: "Blog Tags Retrieve",
        description: "Endpoint for retrieving blog tags",
        method: "GET",
        route: "/v3/api/custom/lambda/blog/tags",
        inputs: [
          { name: "limit", type: "query", rules: "", dataType: "Integer" },
          { name: "page", type: "query", rules: "", dataType: "Integer" },
          { name: "name", type: "query", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: false, valueType: "Boolean", parent: "" },
          { id: "data", key: "data", value: [], valueType: "Array", parent: "" },
          { id: "limit", key: "limit", value: 10, valueType: "Integer", parent: "" },
          { id: "page", key: "page", value: 1, valueType: "Integer", parent: "" },
          { id: "total", key: "total", value: 0, valueType: "Integer", parent: "" },
          { id: "num_pages", key: "num_pages", value: 0, valueType: "Integer", parent: "" }
        ],
        code: `

        app.get("/v3/api/custom/lambda/blog/tags", publicMiddlewares, async function (req, res) {
            try {
        
              let sdk = req.sdk; 
              sdk.getDatabase();
              sdk.setProjectId(req.projectId);
              sdk.setTable('blog_tags')
  
              let limit = parseInt(req.query.limit) ? parseInt(req.query.limit) : 10 ;
              let page = parseInt(req.query.page) ? parseInt(req.query.page) :  1;
              let offset = (page - 1) * limit;
  
              let {name} = req.query;
  
              let tags = await sdk.rawQuery(\`select * from \${req.projectId}_blog_tags where 1=1 \${name ? " and name like '%" + name + "%'" : ""}\`)
  
              
        
              return res.status(200).json({ error: false, data: tags.slice(offset, offset + limit),  limit, page, total: tags.length, num_pages: ((tags.length+limit-1)/limit).toFixed(0) });
            } catch (err) {
              console.error(err);
              res.status(404);
              res.json({
                error: true,
                message: err.message,
              });
            }
      });
        
        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogTagsDelete",
        name: "Blog Tags Delete by ID",
        description: "Endpoint for deleting a blog tag by ID",
        method: "DELETE",
        route: "/v3/api/custom/lambda/blog/tags/:id",
        inputs: [
          { name: "id", type: "path", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: false, valueType: "Boolean", parent: "" },
          { id: "message", key: "message", value: "Tag Deleted", valueType: "String", parent: "" }
        ],
        code: `
                    
            app.delete("/v3/api/custom/lambda/blog/tags/:id", middlewares, TokenMiddleware(),  async function (req, res) {
                try {
            
                let sdk = req.sdk; 
                sdk.getDatabase();
                sdk.setProjectId(req.projectId);
                sdk.setTable('blog_tags')
        
                if(req.role != 'admin') throw new Error('Unauthorized');
        
                sdk.setTable('blog_tags')
                await sdk.deleteWhere({id: req.params.id})
        
                sdk.setTable('blog_post_tags');
        
                await await sdk.deleteWhere({tag_id: req.params.id})
        
                return res.status(200).json({ error: false, message: "Tag Deleted" });
                } catch (err) {
                console.error(err);
                res.status(404);
                res.json({
                    error: true,
                    message: err.message,
                });
                }
        });

        `,
        doc: "",
        unit: "",
        protected: true,
        authorizedRoles: ["admin"],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogCategoryCreate",
        name: "Create Blog Category",
        description: "Endpoint for creating a new blog category",
        method: "POST",
        route: "/v3/api/custom/lambda/blog/category",
        inputs: [
          { name: "name", type: "body", rules: "", dataType: "String" },
          { name: "parent_id", type: "body", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: false, valueType: "Boolean", parent: "" },
          { id: "data", key: "data", value: "", valueType: "String", parent: "" }
        ],
        code: `
        
            app.post("/v3/api/custom/lambda/blog/category", publicMiddlewares, async function (req, res) {
                try {
            
                let sdk = req.sdk; 
                sdk.getDatabase();
                sdk.setProjectId(req.projectId);
                sdk.setTable('blog_category')
    
                let {name, parent_id} = req.body;
    
                let parentExist = await sdk.get({id: parent_id});
    
                if(!parentExist) throw new Error("Parent Doesn't Exists")
    
                let r = await sdk.insert({
                    name,
                    parent_id,
                    create_at: sqlDateFormat(new Date()),
                    update_at: sqlDateTimeFormat(new Date())
                })
    
                
            
                return res.status(200).json({ error: false, data: r });
                } catch (err) {
                console.error(err);
                res.status(404);
                res.json({
                    error: true,
                    message: err.message,
                });
                }
        });

        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogCategoryUpdate",
        name: "Update Blog Category",
        description: "Endpoint for updating a blog category",
        method: "POST",
        route: "/v3/api/custom/lambda/blog/category/:id",
        inputs: [
          { name: "name", type: "body", rules: "", dataType: "String" },
          { name: "parent_id", type: "body", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: false, valueType: "Boolean", parent: "" },
          { id: "data", key: "data", value: "Updated", valueType: "String", parent: "" }
        ],
        code: `

            app.post("/v3/api/custom/lambda/blog/category/:id", publicMiddlewares, async function (req, res) {
                try {
            
                let sdk = req.sdk; 
                sdk.getDatabase();
                sdk.setProjectId(req.projectId);
                sdk.setTable('blog_category')
        
                let {name, parent_id} = req.body;
        
                let parentExist = await sdk.get({id: parent_id});
        
                if(!parentExist) throw new Error("Parent Doesn't Exists")
        
                let r = await sdk.updateWhere({
                    name,
                    parent_id,
                    create_at: sqlDateFormat(new Date()),
                    update_at: sqlDateTimeFormat(new Date())
                }, {id: req.params.id})
        
                
            
                return res.status(200).json({ error: false, data: "Updated" });
                } catch (err) {
                console.error(err);
                res.status(404);
                res.json({
                    error: true,
                    message: err.message,
                });
                }
        });
        
        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogCategoryGet",
        name: "Get Blog Category",
        description: "Endpoint for retrieving blog categories",
        method: "GET",
        route: "/v3/api/custom/lambda/blog/category",
        inputs: [
          { name: "limit", type: "query", rules: "", dataType: "Integer" },
          { name: "page", type: "query", rules: "", dataType: "Integer" },
          { name: "name", type: "query", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: "false", valueType: "Boolean", parent: "" },
          { id: "data", key: "data", value: "", valueType: "Array", parent: "" },
          { id: "limit", key: "limit", value: "", valueType: "Integer", parent: "" },
          { id: "page", key: "page", value: "", valueType: "Integer", parent: "" },
          { id: "total", key: "total", value: "", valueType: "Integer", parent: "" },
          { id: "num_pages", key: "num_pages", value: "", valueType: "String", parent: "" }
        ],
        code: `
        
        app.get("/v3/api/custom/lambda/blog/category", publicMiddlewares, async function (req, res) {
            try {
        
              let sdk = req.sdk; 
              sdk.getDatabase();
              sdk.setProjectId(req.projectId);
              sdk.setTable('blog_category')
  
              let limit = parseInt(req.query.limit) ? parseInt(req.query.limit) : 10 ;
              let page = parseInt(req.query.page) ? parseInt(req.query.page) :  1;
              let offset = (page - 1) * limit;
  
              let {name} = req.query;
  
              let categories = await sdk.rawQuery(\`select * from \${req.projectId}_blog_category where 1=1 \${name ? " and name like '%" + name + "%'" : ""}\`)
  
              
        
              return res.status(200).json({ error: false, data: categories.slice(offset, offset + limit),  limit, page, total: categories.length, num_pages: ((categories.length+limit-1)/limit).toFixed(0) });
            } catch (err) {
              console.error(err);
              res.status(404);
              res.json({
                error: true,
                message: err.message,
              });
            }
      });

        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogSubcategoryGet",
        name: "Get Blog Subcategory",
        description: "Endpoint for retrieving subcategories of a blog category",
        method: "GET",
        route: "/v3/api/custom/lambda/blog/subcategory/:id",
        inputs: [
          { name: "id", type: "path", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: "false", valueType: "Boolean", parent: "" },
          { id: "data", key: "data", value: "", valueType: "Array", parent: "" }
        ],
        code: `
        
        
        app.get("/v3/api/custom/lambda/blog/subcategory/:id", publicMiddlewares, async function (req, res) {
            try {
        
              let sdk = req.sdk; 
              sdk.getDatabase();
              sdk.setProjectId(req.projectId);
              sdk.setTable('blog_category')
  
  
              let subcategories = await sdk.get({parent_id: req.params.id})
  
              
        
              return res.status(200).json({ error: false, data: subcategories });
            } catch (err) {
              console.error(err);
              res.status(404);
              res.json({
                error: true,
                message: err.message,
              });
            }
      });
        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      },
      {
        id: "blogDeleteCategory",
        name: "Delete Blog Category",
        description: "Endpoint for deleting a blog category",
        method: "DELETE",
        route: "/v3/api/custom/lambda/blog/category/:id",
        inputs: [
          { name: "id", type: "path", rules: "", dataType: "String" }
        ],
        response: [
          { id: "error", key: "error", value: "false", valueType: "Boolean", parent: "" },
          { id: "data", key: "data", value: "Deleted", valueType: "String", parent: "" }
        ],
        code: `
        
        app.delete("/v3/api/custom/lambda/blog/category/:id", publicMiddlewares, async function (req, res) {
            try {
        
              let sdk = req.sdk; 
              sdk.getDatabase();
              sdk.setProjectId(req.projectId);
              sdk.setTable('blog_category')
  
  
              await recursiveDeleteCategory(req.params.id, sdk);
  
              
        
              return res.status(200).json({ error: false, data: "Deleted" });
            } catch (err) {
              console.error(err);
              res.status(404);
              res.json({
                error: true,
                message: err.message,
              });
            }
      });
        
        `,
        doc: "",
        unit: "",
        protected: false,
        authorizedRoles: [],
        imports: "",
        type: "default",
        group: "blog"
      }         
      
      
];


export const blogImports = `

const ProjectMiddleware = require("../../../middleware/ProjectMiddleware");
const UrlMiddleware = require("../../../middleware/UrlMiddleware");
const HostMiddleware = require("../../../middleware/HostMiddleware");
const TokenMiddleware = require("../../../middleware/TokenMiddleware");
const PermissionMiddleware = require("../../../middleware/PermissionMiddleware");
const {sqlDateFormat, sqlDateTimeFormat} = require("../../../services/UtilService")

const middlewares = [ProjectMiddleware, UrlMiddleware, HostMiddleware, TokenMiddleware()];
const publicMiddlewares = [ProjectMiddleware, UrlMiddleware, HostMiddleware];

const config = require("../../../config");



async function includeTagsAndCategories(blogs, sdk){
    for(let blog of blogs){
      let tags = await sdk.join('blog_post_tags', 'blog_tags', 'tag_id', 'id', 'name, blog_tags.id', {post_id: blog.id});
      let categories = await sdk.join('blog_post_category', 'blog_category', 'category_id', 'id', 'name, blog_category.id', {post_id: blog.id});
      sdk.setTable('blog_post_views');
      let views = await sdk.get({post_id: blog.id })
      blog.tags = tags,
      blog.categories = categories
      blog.views = views.length
    }

    return blogs;
  }


  async function recursiveDeleteCategory(category_id, sdk){
    sdk.setTable('blog_category');
    let children = await sdk.get({parent_id: category_id});

    await sdk.deleteWhere({
        id: category_id
    });

    for(let x of children){
         recursiveDeleteCategory(x.id, sdk);
    }
}

`