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

const external_accountsRoutes = require('./routes/external_accounts');

const skill_nodesRoutes = require('./routes/skill_nodes');

const user_skill_node_awardsRoutes = require('./routes/user_skill_node_awards');

const projectsRoutes = require('./routes/projects');

const external_signalsRoutes = require('./routes/external_signals');

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

const course_phasesRoutes = require('./routes/course_phases');

const lessonsRoutes = require('./routes/lessons');

const lesson_variantsRoutes = require('./routes/lesson_variants');

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

const build_tasksRoutes = require('./routes/build_tasks');

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

const lesson_progressRoutes = require('./routes/lesson_progress');

const quiz_attemptsRoutes = require('./routes/quiz_attempts');

const task_submissionsRoutes = require('./routes/task_submissions');

const ai_chat_sessionsRoutes = require('./routes/ai_chat_sessions');

const ai_chat_messagesRoutes = require('./routes/ai_chat_messages');

const career_coach_reportsRoutes = require('./routes/career_coach_reports');

const usage_limitsRoutes = require('./routes/usage_limits');

const pricing_plansRoutes = require('./routes/pricing_plans');

const subscriptionsRoutes = require('./routes/subscriptions');

const paymentsRoutes = require('./routes/payments');

const cohortsRoutes = require('./routes/cohorts');

const organization_membershipsRoutes = require('./routes/organization_memberships');

const talent_inquiriesRoutes = require('./routes/talent_inquiries');


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: "Matthew LMS",
        description: "Matthew LMS 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/onboarding_responses', passport.authenticate('jwt', {session: false}), onboarding_responsesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
