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

const connected_systemsRoutes = require('./routes/connected_systems');

const control_frameworksRoutes = require('./routes/control_frameworks');

const control_requirementsRoutes = require('./routes/control_requirements');

const identity_workflowsRoutes = require('./routes/identity_workflows');

const evidence_modelsRoutes = require('./routes/evidence_models');

const artifactsRoutes = require('./routes/artifacts');

const sampled_subjectsRoutes = require('./routes/sampled_subjects');

const proof_packetsRoutes = require('./routes/proof_packets');

const remediation_itemsRoutes = require('./routes/remediation_items');

const access_reviewsRoutes = require('./routes/access_reviews');

const access_review_itemsRoutes = require('./routes/access_review_items');

const exceptionsRoutes = require('./routes/exceptions');

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

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

const organization_settingsRoutes = require('./routes/organization_settings');

const artifact_type_catalogRoutes = require('./routes/artifact_type_catalog');

const workflow_templatesRoutes = require('./routes/workflow_templates');


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: "Identity Evidence Accelerator",
        description: "Identity Evidence Accelerator 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/user_invitations', passport.authenticate('jwt', {session: false}), user_invitationsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
