export const ecommerce = [
    {
        id: 'ecomProductLambda',
        name: 'Retrieve Product Lambda',
        method: 'POST',
        description: 'Endpoint to retrieve e-commerce products with pagination.',
        route: '/v3/api/custom/lambda/ecom/product/',
        inputs: [
          { id: 'page', name: 'page', type: 'body', rules: 'required', dataType: 'Number', value: '' },
          { id: 'limit', name: 'limit', type: 'body', rules: 'required', dataType: 'Number', value: '' },
          { id: 'sortId', name: 'sortId', type: 'body', rules: 'optional', dataType: 'String', value: '' },
          { id: 'direction', name: 'direction', type: 'body', rules: 'optional', dataType: 'String', value: '' }
        ],
        response: [
            { id: "error", key: 'error', value: "false", valueType: 'Boolean', parent: '' },
            { id: "message", key: 'message', value: '', valueType: 'String', parent: '' },
            { id: "page", key: 'page', value: '', valueType: 'Number', parent: '' },
            { id: "limit", key: 'limit', value: '', valueType: 'Number', parent: '' },
            { id: "total", key: 'total', value: '', valueType: 'Number', parent: '' },
            { id: "num_pages", key: 'num_pages', value: '', valueType: 'Number', parent: '' }
        ],
        code: `app.post("/v3/api/lambda/ecom/product/", [...middlewares], async function (req, res) {
          try {
            let sdk = req.sdk;
            req.projectId;
            sdk.setProjectId(req.projectId);
            const db = await sdk.getDatabase();
            const productTable = \`\${req.projectId}_ecom_product\`;
            const categoryTable = \`\${req.projectId}_ecom_category\`;
      
            let sql = \`SELECT 
            \${productTable}.id as product_id,
            \${productTable}.name as product_name,
            \${productTable}.category_id AS "category",
            \${productTable}.subcategory_id AS "subcategory",
            \${categoryTable}.name as category_name,
            \${categoryTable}.parent_id as category_parent_id,
            \${categoryTable}.position as category_position,
            \${productTable}.type,
            \${productTable}.parent_id,
            \${productTable}.is_taxable,
            \${productTable}.is_shipping,
            \${productTable}.description,
            \${productTable}.is_sticky,
            \${productTable}.is_featured,
            \${productTable}.is_virtual,
            \${productTable}.is_downloadable,
            \${productTable}.download_limit,
            \${productTable}.is_backorder,
            \${productTable}.sold_single,
            \${productTable}.manage_stock,
            \${productTable}.quantity,
            \${productTable}.thumbnail_image,
            \${productTable}.featured_image,
            \${productTable}.image,
            \${productTable}.data,
            \${productTable}.slug,
            \${productTable}.sku,
            \${productTable}.weight,
            \${productTable}.height,
            \${productTable}.length,
            \${productTable}.weight_unit,
            \${productTable}.height_unit,
            \${productTable}.length_unit,
            \${productTable}.avg_review,
            \${productTable}.sale_price,
            \${productTable}.shipping_price,
            \${productTable}.regular_price,
            \${productTable}.status,
            \${productTable}.position as product_position,
            \${productTable}.download_expire_at,
            \${productTable}.schedule_sale_at,
            \${productTable}.schedule_sale_end FROM \${categoryTable} JOIN \${productTable} ON \${categoryTable}.id=\${productTable}.category_id 
            \`;
            // OR \${categoryTable}.id=\${productTable}.subcategory_id
      
            const validationResult = await ValidationService.validateInputMethod(
              {
                page: "required",
                limit: "required"
              },
              {
                page: "page is missing",
                limit: "limit is missing"
              },
              req
            );
      
            if (validationResult.error) {
              return res.status(403).json(validationResult);
            }
      
            let modelConfiguration = {};
            // if (validationJSON.models) {
            //   modelConfiguration = validationJSON.models;
            // }
      
            let paginationService = new PaginationService(req.body.page, req.body.limit);
            paginationService.setSortField(req.body.sortId);
            paginationService.setSortDirection(req.body.direction);
      
            const page = paginationService.getPage(),
              limit = paginationService.getLimit();
      
            console.log("sql", sql);
      
            const offset = (page - 1) * limit;
      
            sql += \` LIMIT \${offset} , \${limit}\`;
            console.log("sql", sql);
      
            const result = await sdk.rawQuery(sql);
            paginationService.setCount(result.length);
      
            let blacklistFields = [];
      
            if (modelConfiguration && modelConfiguration[req.params.table] && modelConfiguration[req.params.table].mapping) {
              mapping = modelConfiguration[req.params.table].mapping;
            }
      
            if (modelConfiguration && modelConfiguration[req.params.table] && modelConfiguration[req.params.table].return_blacklist_field) {
              blacklistFields = modelConfiguration[req.params.table].return_blacklist_field;
            }
      
            console.log("sql", sql);
            // // console.log('bind', bind);
            // const result = await sdk.rawQuery(sql);
      
            res.status(200);
      
            const response = result.map((row) => {
              return sdk.blacklistField(row, blacklistFields);
            });
      
            return res.status(200).json({
              error: false,
              list: response,
              page: paginationService.getPage(),
              limit: paginationService.getLimit(),
              total: paginationService.getCount(),
              num_pages: paginationService.getNumPages()
            });
          } catch (err) {
            res.status(403);
            res.json({
              error: true,
              message: err.message
            });
          }
        });`,
        doc: '',
        unit: '',
        protected: true,
        authorizedRoles: [],
        imports: '',
        type: 'lambda',
        group: 'ecom'
      },
      {
        id: 'ecomProductByIdLambda',
        name: 'Ecom Product by ID Lambda',
        method: 'GET',
        description: 'Endpoint to retrieve a specific e-commerce product by ID or slug.',
        route: '/v3/api/custom/lambda/ecom/product/:product_identifier',
        inputs: [
          { id: 'product_identifier', name: 'product_identifier', type: 'params', rules: 'required', dataType: 'String', value: '' }
        ],
        response: [
          { id: 'error', name: 'error', dataType: 'Boolean', description: 'Indicates whether an error occurred.' },
          { id: 'model', name: 'model', dataType: 'Object', description: 'Details of the e-commerce product.' }
        ],
        code: `app.get("/v2/api/lambda/ecom/product/:product_identifier", [...middlewares], async function (req, res) {
          try {
            // ... (existing code)
      
            return res.status(200).json({
              error: false,
              model: result[0]
            });
          } catch (err) {
            res.status(403);
            res.json({
              error: true,
              message: err.message
            });
          }
        });`,
        doc: '',
        unit: '',
        protected: true,
        authorizedRoles: [],
        imports: '',
        type: 'lambda',
        group: 'ecom'
      },
      {
        id: 'ecomProductAddLambda',
        name: 'Add Ecom Product Lambda',
        method: 'POST',
        description: 'Create Product.',
        route: '/v3/api/custom/lambda/ecom/product/add',
        inputs: [
            { id: 'slug', name: 'slug', type: 'body', rules: 'required', dataType: 'String', value: '' },
            { id: 'category_id', name: 'category_id', type: 'body', rules: 'required', dataType: 'String', value: '' },
            { id: 'type', name: 'type', type: 'body', rules: 'required', dataType: 'String', value: '' },
            { id: 'quantity', name: 'quantity', type: 'body', rules: 'required', dataType: 'String', value: '' },
            { id: 'data', name: 'data', type: 'body', rules: 'required', dataType: 'String', value: '' },
            { id: 'name', name: 'name', type: 'body', rules: 'required', dataType: 'String', value: '' },
            { id: 'is_taxable', name: 'is_taxable', type: 'body', rules: '', dataType: 'Boolean', value: '' },
            { id: 'is_shipping', name: 'is_shipping', type: 'body', rules: '', dataType: 'Boolean', value: '' },
            { id: 'is_sticky', name: 'is_sticky', type: 'body', rules: '', dataType: 'Boolean', value: '' },
            { id: 'is_featured', name: 'is_featured', type: 'body', rules: '', dataType: 'Boolean', value: '' },
            { id: 'is_downloadable', name: 'is_downloadable', type: 'body', rules: '', dataType: 'Boolean', value: '' },
            { id: 'download_limit', name: 'download_limit', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'is_backorder', name: 'is_backorder', type: 'body', rules: '', dataType: 'Boolean', value: '' },
            { id: 'sold_single', name: 'sold_single', type: 'body', rules: '', dataType: 'Boolean', value: '' },
            { id: 'manage_stock', name: 'manage_stock', type: 'body', rules: '', dataType: 'Boolean', value: '' },
            { id: 'thumbnail_image', name: 'thumbnail_image', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'featured_image', name: 'featured_image', type: 'body', rules: '', dataType: 'Boolean', value: '' },
            { id: 'image', name: 'image', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'sku', name: 'sku', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'weight', name: 'weight', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'height', name: 'height', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'length', name: 'length', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'weight_unit', name: 'weight_unit', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'height_unit', name: 'height_unit', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'length_unit', name: 'length_unit', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'avg_review', name: 'avg_review', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'sale_price', name: 'sale_price', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'shipping_price', name: 'shipping_price', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'regular_price', name: 'regular_price', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'position', name: 'position', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'download_expire_at', name: 'download_expire_at', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'schedule_sale_at', name: 'schedule_sale_at', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'schedule_sale_end', name: 'schedule_sale_end', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'description', name: 'description', type: 'body', rules: '', dataType: 'String', value: '' },
            { id: 'is_virtual', name: 'is_virtual', type: 'body', rules: '', dataType: 'Boolean', value: '' }
          ],
        response: [
            { id: "error", key: 'error', value: "false", valueType: 'Boolean', parent: '' },
            { id: "message", key: 'message', value: '', valueType: 'String', parent: '' },
        ],
        code: `  app.post("/v2/api/lambda/ecom/product/add", [...middlewares, TokenMiddleware({ role: "admin|user|customer|member" })], async function (req, res) {
            try {
                let sdk = req.sdk;
                sdk.getDatabase();
                sdk.setProjectId(req.projectId);
                const {slug, category_id, type, quantity,data,name} = req.body
                if(!stringChecker.isStringNonEmpty([category_id, quantity, name, slug])){
                  return res.status(403).json({
                    error: true,
                    message: "One or More Missing fields",
                    validation: [{ field: "name,category_id,type, quantity, data", message: "product name or category or quantity or type or data missing" }],
                  });
                }
                
                
                sdk.setTable("ecom_category")
                const category = await sdk.get({
                  id:category_id
                })
                
                if (typeof category == "string") {
                  return res.status(403).json({
                    error: true,
                    message: "Invalid Category",
                    validation: [{ field: "category_id", message: "Category Missing" }],
                  });
                }
        
              sdk.setTable("ecom_product");
              const products = await sdk.get({
                slug
              });
              if (products.length > 0) {
                return res.status(403).json({
                  error: true,
                  message: "Slug has already been used",
                  validation: [{ field: "slug", message: "Used Slug" }]
                });
              }
              const payload = req.body;
              const productId = await sdk.insert({
                category_id,
                type : req.body.type ?? 0,
                quantity,
                data: data ?? ' ',
                name,
                parent_id : req.body.type ?? 0,
                subcategory_id : req.body.type ?? 0,
                is_taxable: req.body.is_taxable || 0,
                is_shipping: req.body.is_shipping || 0,
                is_sticky: req.body.is_sticky || 0,
                is_featured: req.body.is_featured || 0,
                is_downloadable: req.body.is_downloadable || 0,
                download_limit:req.body.download_limit ?? 0,
                is_backorder: req.body.is_backorder || 0,
                sold_single: req.body.sold_single,
                manage_stock: req.body.manage_stock,
                thumbnail_image:req.body.thumbnail_image,
                featured_image:req.body.featured_image,
                image:req.body.image,
                sku:req.body.sku,
                weight:req.body.weight,
                height:req.body.height,
                length:req.body.length,
                weight_unit: req.body.weight_unit,
                height_unit: req.body.height_unit,
                length_unit: req.body.length_unit,
                avg_review:req.body.avg_review ?? 0,
                sale_price:req.body.sale_price,
                shipping_price:req.body.shipping_price,
                regular_price:req.body.regular_price,
                status:0,
                position: req.body.position ?? 0,
                download_expire_at: req.body.download_expire_at,
                schedule_sale_at: req.body.schedule_sale_at,
                schedule_sale_end: req.body.schedule_sale_end,
                description: req.body.description || "",
                is_virtual: req.body.is_virtual || 0,
                slug,
                create_at: sqlDateTimeFormat(new Date()),
                update_at: sqlDateTimeFormat(new Date())
              });
              if(req.body.download_link){
                sdk.setTable("ecom_product_link");
                await sdk.insert({
                  product_id: productId,
                  link:req.body.download_link,
                  create_at: sqlDateTimeFormat(new Date()),
                  update_at: sqlDateTimeFormat(new Date())
                })
              }
        
              return res.status(200).json({
                error: false,
                message: \`Product Successfully Created\`
              });
            } catch (err) {
              res.status(403);
              res.json({
                error: true,
                message: err.message
              });
            }
          });`,
        doc: '',
        unit: '',
        protected: true,
        authorizedRoles: [],
        imports: '',
        type: 'lambda',
        group: 'ecom'
      },
      {
        id: 'ecomProductEditLambda',
        name: 'Edit Ecom Product Lambda',
        method: 'PUT',
        description: 'Edit Product.',
        route: '/v3/api/custom/lambda/ecom/product/:id',
        inputs: [
            { id: 'id', name: 'id', type: 'path', rules: 'required', dataType: 'Number', value: '' },
            { id: 'payload', name: 'payload', type: 'body', rules: 'required', dataType: 'Object', value: '' },
          ],
        response: [
            { id: "error", key: 'error', value: "false", valueType: 'Boolean', parent: '' },
            { id: "message", key: 'message', value: '', valueType: 'String', parent: '' },
        ],
        code: `  app.put("/v3/api/custom/lambda/ecom/product/:id", [...middlewares, TokenMiddleware({ role: "admin|user|customer|member" })], async function (req, res) {
            try {
              let sdk = req.sdk;
              req.projectId;
              sdk.setProjectId(req.projectId);
              sdk.setTable("ecom_product");
              const result = await sdk.get({
                id: req.params.id
              });
              if (result.length <= 0) {
                return res.status(403).json({
                  error: true,
                  message: "Something went wrong"
                });
              }
              const payload = req.body;
              const id = req.params.id;
        
              await sdk.update(
                {
                  ...payload,
                  update_at: sqlDateTimeFormat(new Date())
                },
                id
              );
        
              return res.status(200).json({
                error: false,
                message: \`successfully Edited \${id}\`
              });
            } catch (err) {
              res.status(403);
              res.json({
                error: true,
                message: err.message
              });
            }
          });`,
        doc: '',
        unit: '',
        protected: true,
        authorizedRoles: [],
        imports: '',
        type: 'lambda',
        group: 'ecom'
      },
      {
        id: 'ecomProductDeleteLambda',
        name: 'Delete Ecom Product Lambda',
        method: 'DELETE',
        description: 'Delete Product.',
        route: '/v3/api/custom/lambda/ecom/product/:id',
        inputs: [
            { id: 'id', name: 'id', type: 'path', rules: 'required', dataType: 'Number', value: '' },
          ],
        response: [
            { id: "error", key: 'error', value: "false", valueType: 'Boolean', parent: '' },
            { id: "message", key: 'message', value: '', valueType: 'String', parent: '' },
        ],
        code: `  app.delete("/v3/api/custom/lambda/ecom/product/:id", [...middlewares, TokenMiddleware({ role: "admin|user|customer|member" })], async function (req, res) {
            try {
              let sdk = req.sdk;
              sdk.getDatabase();
              sdk.setProjectId(req.projectId);
              sdk.setTable("ecom_product");
              const result = await sdk.get({
                id: req.params.id
              });
              if (result.length <= 0) {
                return res.status(403).json({
                  error: true,
                  message: "Something went wrong"
                });
              }
        
              await sdk.delete({}, req.params.id);
        
              return res.status(200).json({
                error: false,
                message: "successfully deleted"
              });
            } catch (err) {
              res.status(403);
              res.json({
                error: true,
                message: err.message
              });
            }
          });`,
        doc: '',
        unit: '',
        protected: true,
        authorizedRoles: [],
        imports: '',
        type: 'lambda',
        group: 'ecom'
      },
      
      
]


export const ecommerceImports = `

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 StripeService = require("../../../services/StripeService");
const ValidationService = require("../../../services/ValidationService");
const PaginationService = require("../../../services/PaginationService");
const { stringChecker, dateChecker } = require("../../../utils/helpers");
const { sqlDateTimeFormat, sqlDateFormat, filterEmptyFields } = require("../../../services/UtilService");
const config = require("../../../config");
const SyncStripeWebhook = require("../../../middleware/SyncStripeWebhook");
const UploadService = require("../../../services/UploadService");
const AnalyticMiddleware = require("../../../middleware/AnalyticMiddleware");
const upload = UploadService.local_upload();
const SalesTax = require("sales-tax");
const EcomService = require("../../../services/EcomService");

const middlewares = [
  ProjectMiddleware,
  UrlMiddleware,
  HostMiddleware,
  // PermissionMiddleware
  // RateLimitMiddleware,
  // LogMiddleware,
  // UsageMiddleware
  // CheckProjectMiddleware,
  // AnalyticMiddleware,
  // RoleMiddleware
];

const stripeMiddlewares = [
  ProjectMiddleware,
  UrlMiddleware,
  HostMiddleware,
  TokenMiddleware({ role: "admin|user|customer|member" }),
  // PermissionMiddleware,
  SyncStripeWebhook
  // RateLimitMiddleware,
  // LogMiddleware,
  // UsageMiddleware
  // CheckProjectMiddleware,
  // AnalyticMiddleware,
  // RoleMiddleware
];

`