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

const role_assignmentsRoutes = require('./routes/role_assignments');

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

const team_membershipsRoutes = require('./routes/team_memberships');

const programsRoutes = require('./routes/programs');

const learning_pathsRoutes = require('./routes/learning_paths');

const missionsRoutes = require('./routes/missions');

const checklistsRoutes = require('./routes/checklists');

const checklist_itemsRoutes = require('./routes/checklist_items');

const enrollmentsRoutes = require('./routes/enrollments');

const mission_attemptsRoutes = require('./routes/mission_attempts');

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

const quiz_questionsRoutes = require('./routes/quiz_questions');

const quiz_choicesRoutes = require('./routes/quiz_choices');

const quiz_submissionsRoutes = require('./routes/quiz_submissions');

const quiz_answersRoutes = require('./routes/quiz_answers');

const simulationsRoutes = require('./routes/simulations');

const simulation_stepsRoutes = require('./routes/simulation_steps');

const content_assetsRoutes = require('./routes/content_assets');

const ai_content_requestsRoutes = require('./routes/ai_content_requests');

const knowledge_gap_assessmentsRoutes = require('./routes/knowledge_gap_assessments');

const badgesRoutes = require('./routes/badges');

const user_badgesRoutes = require('./routes/user_badges');

const point_ledger_entriesRoutes = require('./routes/point_ledger_entries');

const challengesRoutes = require('./routes/challenges');

const challenge_participantsRoutes = require('./routes/challenge_participants');

const reward_catalog_itemsRoutes = require('./routes/reward_catalog_items');

const reward_redemptionsRoutes = require('./routes/reward_redemptions');

const recognition_postsRoutes = require('./routes/recognition_posts');

const coaching_sessionsRoutes = require('./routes/coaching_sessions');

const kpi_definitionsRoutes = require('./routes/kpi_definitions');

const kpi_measurementsRoutes = require('./routes/kpi_measurements');

const qa_evaluationsRoutes = require('./routes/qa_evaluations');

const qa_scorecardsRoutes = require('./routes/qa_scorecards');

const surveysRoutes = require('./routes/surveys');

const survey_questionsRoutes = require('./routes/survey_questions');

const survey_responsesRoutes = require('./routes/survey_responses');

const survey_response_itemsRoutes = require('./routes/survey_response_items');

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

const audit_eventsRoutes = require('./routes/audit_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: "Frontline Onboarding SaaS",
        description: "Frontline Onboarding SaaS 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/role_permissions', passport.authenticate('jwt', {session: false}), role_permissionsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/audit_events', passport.authenticate('jwt', {session: false}), audit_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;
