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

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

const user_role_assignmentsRoutes = require('./routes/user_role_assignments');

const role_permission_mappingsRoutes = require('./routes/role_permission_mappings');

const vendorsRoutes = require('./routes/vendors');

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

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

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

const purchase_requisitionsRoutes = require('./routes/purchase_requisitions');

const purchase_requisition_linesRoutes = require('./routes/purchase_requisition_lines');

const purchase_ordersRoutes = require('./routes/purchase_orders');

const purchase_order_linesRoutes = require('./routes/purchase_order_lines');

const goods_receiptsRoutes = require('./routes/goods_receipts');

const goods_receipt_linesRoutes = require('./routes/goods_receipt_lines');

const vendor_invoicesRoutes = require('./routes/vendor_invoices');

const invoice_linesRoutes = require('./routes/invoice_lines');

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

const departmentsRoutes = require('./routes/departments');

const document_typesRoutes = require('./routes/document_types');

const documentsRoutes = require('./routes/documents');

const document_linksRoutes = require('./routes/document_links');

const approval_workflowsRoutes = require('./routes/approval_workflows');

const approval_stepsRoutes = require('./routes/approval_steps');

const approvalsRoutes = require('./routes/approvals');

const activity_logsRoutes = require('./routes/activity_logs');

const ui_announcementsRoutes = require('./routes/ui_announcements');


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
