
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 openaiRoutes = require('./routes/openai');
const buyerPortalRoutes = require('./routes/buyer_portal');
const integrationsRoutes = require('./routes/integrations');



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

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

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

const accountsRoutes = require('./routes/accounts');

const locationsRoutes = require('./routes/locations');

const contactsRoutes = require('./routes/contacts');

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

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

const inventory_itemsRoutes = require('./routes/inventory_items');

const price_listsRoutes = require('./routes/price_lists');

const price_list_itemsRoutes = require('./routes/price_list_items');

const account_price_listsRoutes = require('./routes/account_price_lists');

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

const quotesRoutes = require('./routes/quotes');

const quote_itemsRoutes = require('./routes/quote_items');

const sample_requestsRoutes = require('./routes/sample_requests');

const saved_listsRoutes = require('./routes/saved_lists');

const saved_list_itemsRoutes = require('./routes/saved_list_items');


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: "B2B Distributor Portal",
        description: "B2B Distributor Portal 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/buyer_portal', passport.authenticate('jwt', {session: false}), buyerPortalRoutes);
app.use('/api/integrations', passport.authenticate('jwt', {session: false}), integrationsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
