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

const project_phasesRoutes = require('./routes/project_phases');

const milestonesRoutes = require('./routes/milestones');

const ore_bodiesRoutes = require('./routes/ore_bodies');

const samplesRoutes = require('./routes/samples');

const chain_of_custody_eventsRoutes = require('./routes/chain_of_custody_events');

const laboratoriesRoutes = require('./routes/laboratories');

const test_type_schemasRoutes = require('./routes/test_type_schemas');

const metallurgical_testsRoutes = require('./routes/metallurgical_tests');

const test_result_pointsRoutes = require('./routes/test_result_points');

const flowsheetsRoutes = require('./routes/flowsheets');

const equipment_itemsRoutes = require('./routes/equipment_items');

const flowsheet_nodesRoutes = require('./routes/flowsheet_nodes');

const flowsheet_streamsRoutes = require('./routes/flowsheet_streams');

const design_criteria_itemsRoutes = require('./routes/design_criteria_items');

const economic_modelsRoutes = require('./routes/economic_models');

const capex_itemsRoutes = require('./routes/capex_items');

const opex_itemsRoutes = require('./routes/opex_items');

const monte_carlo_runsRoutes = require('./routes/monte_carlo_runs');

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

const entity_linksRoutes = require('./routes/entity_links');

const commentsRoutes = require('./routes/comments');

const tasksRoutes = require('./routes/tasks');

const notificationsRoutes = require('./routes/notifications');

const audit_logsRoutes = require('./routes/audit_logs');

const integrationsRoutes = require('./routes/integrations');

const offline_sync_batchesRoutes = require('./routes/offline_sync_batches');


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: "App Preview",
        description: "App Preview 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/projects', passport.authenticate('jwt', {session: false}), projectsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
