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

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



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

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

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

const companiesRoutes = require('./routes/companies');

const business_unitsRoutes = require('./routes/business_units');

const tagsRoutes = require('./routes/tags');

const assetsRoutes = require('./routes/assets');

const tenantsRoutes = require('./routes/tenants');

const leasesRoutes = require('./routes/leases');

const work_ordersRoutes = require('./routes/work_orders');

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

const warehousesRoutes = require('./routes/warehouses');

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

const inventory_transactionsRoutes = require('./routes/inventory_transactions');

const customersRoutes = require('./routes/customers');

const sales_ordersRoutes = require('./routes/sales_orders');

const sales_order_linesRoutes = require('./routes/sales_order_lines');

const invoicesRoutes = require('./routes/invoices');

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

const crm_pipelinesRoutes = require('./routes/crm_pipelines');

const crm_stagesRoutes = require('./routes/crm_stages');

const leadsRoutes = require('./routes/leads');

const activitiesRoutes = require('./routes/activities');

const content_foldersRoutes = require('./routes/content_folders');

const content_itemsRoutes = require('./routes/content_items');

const seo_keywordsRoutes = require('./routes/seo_keywords');

const content_campaignsRoutes = require('./routes/content_campaigns');

const dashboardsRoutes = require('./routes/dashboards');

const reportsRoutes = require('./routes/reports');


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: "Business Command Center",
        description: "Business Command Center 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/companies', passport.authenticate('jwt', {session: false}), companiesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
