
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');

const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');

const openaiRoutes = require('./routes/openai');



const usersRoutes = require('./routes/users');

const rolesRoutes = require('./routes/roles');

const permissionsRoutes = require('./routes/permissions');

const developer_api_keysRoutes = require('./routes/developer_api_keys');

const addressesRoutes = require('./routes/addresses');

const categoriesRoutes = require('./routes/categories');

const brandsRoutes = require('./routes/brands');

const suppliersRoutes = require('./routes/suppliers');

const productsRoutes = require('./routes/products');

const product_variantsRoutes = require('./routes/product_variants');

const collectionsRoutes = require('./routes/collections');

const product_reviewsRoutes = require('./routes/product_reviews');

const wishlist_itemsRoutes = require('./routes/wishlist_items');

const compare_listsRoutes = require('./routes/compare_lists');

const compare_itemsRoutes = require('./routes/compare_items');

const cartsRoutes = require('./routes/carts');

const cart_itemsRoutes = require('./routes/cart_items');

const ordersRoutes = require('./routes/orders');

const order_itemsRoutes = require('./routes/order_items');

const shipping_carriersRoutes = require('./routes/shipping_carriers');

const shipmentsRoutes = require('./routes/shipments');

const paymentsRoutes = require('./routes/payments');

const couponsRoutes = require('./routes/coupons');

const coupon_redemptionsRoutes = require('./routes/coupon_redemptions');

const loyalty_settingsRoutes = require('./routes/loyalty_settings');

const point_ledger_entriesRoutes = require('./routes/point_ledger_entries');

const frequently_bought_together_groupsRoutes = require('./routes/frequently_bought_together_groups');

const frequently_bought_together_itemsRoutes = require('./routes/frequently_bought_together_items');

const ad_placementsRoutes = require('./routes/ad_placements');

const adsRoutes = require('./routes/ads');

const ad_eventsRoutes = require('./routes/ad_events');

const site_settingsRoutes = require('./routes/site_settings');

const footer_content_blocksRoutes = require('./routes/footer_content_blocks');

const social_linksRoutes = require('./routes/social_links');

const footer_linksRoutes = require('./routes/footer_links');

const payment_badgesRoutes = require('./routes/payment_badges');

const newsletter_subscribersRoutes = require('./routes/newsletter_subscribers');

const cms_pagesRoutes = require('./routes/cms_pages');

const push_notificationsRoutes = require('./routes/push_notifications');

const push_subscriptionsRoutes = require('./routes/push_subscriptions');

const seo_entriesRoutes = require('./routes/seo_entries');


const getBaseUrl = (url) => {
  if (!url) return '';
  return url.endsWith('/api') ? url.slice(0, -4) : url;
};

const options = {
  definition: {
    openapi: "3.0.0",
      info: {
        version: "1.0.0",
        title: "Mokam Mokam",
        description: "Mokam Mokam Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.",
      },
    servers: [
      {
        url: getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || config.swaggerUrl,
        description: "Development server",
      }
    ],
    components: {
      securitySchemes: {
        bearerAuth: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT',
        }
      },
      responses: {
        UnauthorizedError: {
          description: "Access token is missing or invalid"
        }
      }
    },
    security: [{
      bearerAuth: []
    }]
  },
  apis: ["./src/routes/*.js"],
};

const specs = swaggerJsDoc(options);
app.use('/api-docs', function (req, res, next) {
    swaggerUI.host = getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || req.get('host');
    next()
  }, swaggerUI.serve, swaggerUI.setup(specs))

app.use(cors({origin: true}));
require('./auth/auth');

app.use(bodyParser.json());

app.use('/api/auth', authRoutes);
app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.enable('trust proxy');


app.use('/api/users', passport.authenticate('jwt', {session: false}), usersRoutes);

app.use('/api/roles', passport.authenticate('jwt', {session: false}), rolesRoutes);

app.use('/api/permissions', passport.authenticate('jwt', {session: false}), permissionsRoutes);

app.use('/api/developer_api_keys', passport.authenticate('jwt', {session: false}), developer_api_keysRoutes);

app.use('/api/addresses', passport.authenticate('jwt', {session: false}), addressesRoutes);

app.use('/api/categories', passport.authenticate('jwt', {session: false}), categoriesRoutes);

app.use('/api/brands', passport.authenticate('jwt', {session: false}), brandsRoutes);

app.use('/api/suppliers', passport.authenticate('jwt', {session: false}), suppliersRoutes);

app.use('/api/products', passport.authenticate('jwt', {session: false}), productsRoutes);

app.use('/api/product_variants', passport.authenticate('jwt', {session: false}), product_variantsRoutes);

app.use('/api/collections', passport.authenticate('jwt', {session: false}), collectionsRoutes);

app.use('/api/product_reviews', passport.authenticate('jwt', {session: false}), product_reviewsRoutes);

app.use('/api/wishlist_items', passport.authenticate('jwt', {session: false}), wishlist_itemsRoutes);

app.use('/api/compare_lists', passport.authenticate('jwt', {session: false}), compare_listsRoutes);

app.use('/api/compare_items', passport.authenticate('jwt', {session: false}), compare_itemsRoutes);

app.use('/api/carts', passport.authenticate('jwt', {session: false}), cartsRoutes);

app.use('/api/cart_items', passport.authenticate('jwt', {session: false}), cart_itemsRoutes);

app.use('/api/orders', passport.authenticate('jwt', {session: false}), ordersRoutes);

app.use('/api/order_items', passport.authenticate('jwt', {session: false}), order_itemsRoutes);

app.use('/api/shipping_carriers', passport.authenticate('jwt', {session: false}), shipping_carriersRoutes);

app.use('/api/shipments', passport.authenticate('jwt', {session: false}), shipmentsRoutes);

app.use('/api/payments', passport.authenticate('jwt', {session: false}), paymentsRoutes);

app.use('/api/coupons', passport.authenticate('jwt', {session: false}), couponsRoutes);

app.use('/api/coupon_redemptions', passport.authenticate('jwt', {session: false}), coupon_redemptionsRoutes);

app.use('/api/loyalty_settings', passport.authenticate('jwt', {session: false}), loyalty_settingsRoutes);

app.use('/api/point_ledger_entries', passport.authenticate('jwt', {session: false}), point_ledger_entriesRoutes);

app.use('/api/frequently_bought_together_groups', passport.authenticate('jwt', {session: false}), frequently_bought_together_groupsRoutes);

app.use('/api/frequently_bought_together_items', passport.authenticate('jwt', {session: false}), frequently_bought_together_itemsRoutes);

app.use('/api/ad_placements', passport.authenticate('jwt', {session: false}), ad_placementsRoutes);

app.use('/api/ads', passport.authenticate('jwt', {session: false}), adsRoutes);

app.use('/api/ad_events', passport.authenticate('jwt', {session: false}), ad_eventsRoutes);

app.use('/api/site_settings', passport.authenticate('jwt', {session: false}), site_settingsRoutes);

app.use('/api/footer_content_blocks', passport.authenticate('jwt', {session: false}), footer_content_blocksRoutes);

app.use('/api/social_links', passport.authenticate('jwt', {session: false}), social_linksRoutes);

app.use('/api/footer_links', passport.authenticate('jwt', {session: false}), footer_linksRoutes);

app.use('/api/payment_badges', passport.authenticate('jwt', {session: false}), payment_badgesRoutes);

app.use('/api/newsletter_subscribers', passport.authenticate('jwt', {session: false}), newsletter_subscribersRoutes);

app.use('/api/cms_pages', passport.authenticate('jwt', {session: false}), cms_pagesRoutes);

app.use('/api/push_notifications', passport.authenticate('jwt', {session: false}), push_notificationsRoutes);

app.use('/api/push_subscriptions', passport.authenticate('jwt', {session: false}), push_subscriptionsRoutes);

app.use('/api/seo_entries', passport.authenticate('jwt', {session: false}), seo_entriesRoutes);

app.use(
    '/api/openai',
    passport.authenticate('jwt', { session: false }),
    openaiRoutes,
);
app.use(
    '/api/ai',
    passport.authenticate('jwt', { session: false }),
    openaiRoutes,
);

app.use(
  '/api/search',
  passport.authenticate('jwt', { session: false }),
  searchRoutes);
app.use(
  '/api/sql',
  passport.authenticate('jwt', { session: false }),
  sqlRoutes);

  
const publicDir = path.join(
  __dirname,
  '../public',
);

if (fs.existsSync(publicDir)) {
  app.use('/', express.static(publicDir));

  app.get('*', function(request, response) {
    response.sendFile(
      path.resolve(publicDir, 'index.html'),
    );
  });
}

const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;

  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });

module.exports = app;
