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

const data_sourcesRoutes = require('./routes/data_sources');

const ingestion_pipelinesRoutes = require('./routes/ingestion_pipelines');

const telemetry_eventsRoutes = require('./routes/telemetry_events');

const ai_modelsRoutes = require('./routes/ai_models');

const detectionsRoutes = require('./routes/detections');

const incidentsRoutes = require('./routes/incidents');

const response_playbooksRoutes = require('./routes/response_playbooks');

const response_actionsRoutes = require('./routes/response_actions');

const soc_agentsRoutes = require('./routes/soc_agents');

const threat_actorsRoutes = require('./routes/threat_actors');

const threat_indicatorsRoutes = require('./routes/threat_indicators');

const threat_campaignsRoutes = require('./routes/threat_campaigns');

const attack_map_eventsRoutes = require('./routes/attack_map_events');

const risk_assessmentsRoutes = require('./routes/risk_assessments');

const simulation_labsRoutes = require('./routes/simulation_labs');

const simulation_runsRoutes = require('./routes/simulation_runs');

const infrastructure_clustersRoutes = require('./routes/infrastructure_clusters');

const edge_sensorsRoutes = require('./routes/edge_sensors');

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

const ai_recommendationsRoutes = require('./routes/ai_recommendations');


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: "CyberShield AI Ecosystem",
        description: "CyberShield AI Ecosystem 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/assets', passport.authenticate('jwt', {session: false}), assetsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

db.sequelize.sync().then(function () {
  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });
});

module.exports = app;
