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



const usersRoutes = require('./routes/users');

const rolesRoutes = require('./routes/roles');

const permissionsRoutes = require('./routes/permissions');

const public_profilesRoutes = require('./routes/public_profiles');

const private_profilesRoutes = require('./routes/private_profiles');

const membership_plansRoutes = require('./routes/membership_plans');

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

const stripe_eventsRoutes = require('./routes/stripe_events');

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

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

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

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

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

const trophiesRoutes = require('./routes/trophies');

const user_trophiesRoutes = require('./routes/user_trophies');

const ai_gatewaysRoutes = require('./routes/ai_gateways');

const usage_limit_policiesRoutes = require('./routes/usage_limit_policies');

const ai_tasksRoutes = require('./routes/ai_tasks');

const ai_requestsRoutes = require('./routes/ai_requests');

const ai_outputsRoutes = require('./routes/ai_outputs');

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

const messagesRoutes = require('./routes/messages');

const resume_documentsRoutes = require('./routes/resume_documents');

const feedback_entriesRoutes = require('./routes/feedback_entries');

const tracking_eventsRoutes = require('./routes/tracking_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: "AI Coaching LMS MVP",
        description: "AI Coaching LMS MVP 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/public_profiles', passport.authenticate('jwt', {session: false}), public_profilesRoutes);

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

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

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

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

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

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

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/artifacts', passport.authenticate('jwt', {session: false}), artifactsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

  
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;
