
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 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 organizationForAuthRoutes = require('./routes/organizationLogin');

const openaiRoutes = require('./routes/openai');
const vortaCommerceRoutes = require('./routes/vortaCommerce');
const vortaUniverseRoutes = require('./routes/vortaUniverse');



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

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

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

const organizationsRoutes = require('./routes/organizations');

const trust_profilesRoutes = require('./routes/trust_profiles');

const identity_verificationsRoutes = require('./routes/identity_verifications');

const walletsRoutes = require('./routes/wallets');

const wallet_transactionsRoutes = require('./routes/wallet_transactions');

const chatsRoutes = require('./routes/chats');

const chat_participantsRoutes = require('./routes/chat_participants');

const messagesRoutes = require('./routes/messages');

const storesRoutes = require('./routes/stores');

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

const product_categoriesRoutes = require('./routes/product_categories');

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

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

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

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

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

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

const postsRoutes = require('./routes/posts');

const deep_dive_linksRoutes = require('./routes/deep_dive_links');

const citationsRoutes = require('./routes/citations');

const post_engagementsRoutes = require('./routes/post_engagements');

const rewardsRoutes = require('./routes/rewards');

const forum_spacesRoutes = require('./routes/forum_spaces');

const forum_threadsRoutes = require('./routes/forum_threads');

const forum_postsRoutes = require('./routes/forum_posts');

const job_companiesRoutes = require('./routes/job_companies');

const job_listingsRoutes = require('./routes/job_listings');

const job_applicationsRoutes = require('./routes/job_applications');

const user_credentialsRoutes = require('./routes/user_credentials');

const affiliate_programsRoutes = require('./routes/affiliate_programs');

const affiliate_membershipsRoutes = require('./routes/affiliate_memberships');

const commissionsRoutes = require('./routes/commissions');

const geo_rulesRoutes = require('./routes/geo_rules');

const facta_queriesRoutes = require('./routes/facta_queries');

const facta_answersRoutes = require('./routes/facta_answers');

const subscriptionsRoutes = require('./routes/subscriptions');

const api_clientsRoutes = require('./routes/api_clients');

const audit_eventsRoutes = require('./routes/audit_events');


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: "Vorta Universe MVP",
        description: "Vorta Universe MVP 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/organizations', passport.authenticate('jwt', {session: false}), organizationsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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/payments', passport.authenticate('jwt', {session: false}), paymentsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/vorta-commerce', passport.authenticate('jwt', {session: false}), vortaCommerceRoutes);
app.use('/api/vorta-universe', passport.authenticate('jwt', {session: false}), vortaUniverseRoutes);

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);

app.use(
  '/api/org-for-auth',
  organizationForAuthRoutes,
  );

  
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;
