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

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

const teamsRoutes = require('./routes/teams');

const membershipsRoutes = require('./routes/memberships');

const identity_providersRoutes = require('./routes/identity_providers');

const user_identitiesRoutes = require('./routes/user_identities');

const policy_rulesRoutes = require('./routes/policy_rules');

const kms_configsRoutes = require('./routes/kms_configs');

const conference_templatesRoutes = require('./routes/conference_templates');

const roomsRoutes = require('./routes/rooms');

const room_invitationsRoutes = require('./routes/room_invitations');

const conferencesRoutes = require('./routes/conferences');

const participantsRoutes = require('./routes/participants');

const conference_nodesRoutes = require('./routes/conference_nodes');

const sfu_allocationsRoutes = require('./routes/sfu_allocations');

const breakout_roomsRoutes = require('./routes/breakout_rooms');

const chat_channelsRoutes = require('./routes/chat_channels');

const chat_messagesRoutes = require('./routes/chat_messages');

const filesRoutes = require('./routes/files');

const room_filesRoutes = require('./routes/room_files');

const recordingsRoutes = require('./routes/recordings');

const transcriptsRoutes = require('./routes/transcripts');

const canvas_documentsRoutes = require('./routes/canvas_documents');

const canvas_eventsRoutes = require('./routes/canvas_events');

const layout_modelsRoutes = require('./routes/layout_models');

const layout_preferencesRoutes = require('./routes/layout_preferences');

const federated_learning_updatesRoutes = require('./routes/federated_learning_updates');

const ai_companion_sessionsRoutes = require('./routes/ai_companion_sessions');

const knowledge_graph_itemsRoutes = require('./routes/knowledge_graph_items');

const external_integrationsRoutes = require('./routes/external_integrations');

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

const coursesRoutes = require('./routes/courses');

const course_enrollmentsRoutes = require('./routes/course_enrollments');

const assignmentsRoutes = require('./routes/assignments');

const submissionsRoutes = require('./routes/submissions');

const quizzesRoutes = require('./routes/quizzes');

const quiz_resultsRoutes = require('./routes/quiz_results');

const marketplace_appsRoutes = require('./routes/marketplace_apps');

const app_installationsRoutes = require('./routes/app_installations');

const app_crash_reportsRoutes = require('./routes/app_crash_reports');

const audit_eventsRoutes = require('./routes/audit_events');

const data_subject_requestsRoutes = require('./routes/data_subject_requests');

const service_incidentsRoutes = require('./routes/service_incidents');

const deployment_changesRoutes = require('./routes/deployment_changes');

const feature_flagsRoutes = require('./routes/feature_flags');

const quality_reportsRoutes = require('./routes/quality_reports');

const event_streamsRoutes = require('./routes/event_streams');

const conference_eventsRoutes = require('./routes/conference_events');


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: "Autonomous Video Platform",
        description: "Autonomous Video Platform 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/tenants', passport.authenticate('jwt', {session: false}), tenantsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
