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

const learner_profilesRoutes = require('./routes/learner_profiles');

const subject_categoriesRoutes = require('./routes/subject_categories');

const subjectsRoutes = require('./routes/subjects');

const languagesRoutes = require('./routes/languages');

const gigsRoutes = require('./routes/gigs');

const gig_levelsRoutes = require('./routes/gig_levels');

const tagsRoutes = require('./routes/tags');

const bookingsRoutes = require('./routes/bookings');

const conversationsRoutes = require('./routes/conversations');

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

const reviewsRoutes = require('./routes/reviews');

const notesRoutes = require('./routes/notes');

const disputesRoutes = require('./routes/disputes');

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

const platform_configRoutes = require('./routes/platform_config');

const admin_audit_logsRoutes = require('./routes/admin_audit_logs');

const user_login_historyRoutes = require('./routes/user_login_history');

const invitesRoutes = require('./routes/invites');

const spacesRoutes = require('./routes/spaces');

const space_membershipsRoutes = require('./routes/space_memberships');

const community_postsRoutes = require('./routes/community_posts');

const community_commentsRoutes = require('./routes/community_comments');

const community_reactionsRoutes = require('./routes/community_reactions');

const community_reportsRoutes = require('./routes/community_reports');

const weekly_challengesRoutes = require('./routes/weekly_challenges');

const challenge_participationsRoutes = require('./routes/challenge_participations');

const user_gamificationRoutes = require('./routes/user_gamification');

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

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

const study_groupsRoutes = require('./routes/study_groups');

const study_group_membershipsRoutes = require('./routes/study_group_memberships');

const study_group_postsRoutes = require('./routes/study_group_posts');

const study_group_messagesRoutes = require('./routes/study_group_messages');

const study_group_resourcesRoutes = require('./routes/study_group_resources');

const live_eventsRoutes = require('./routes/live_events');

const event_rsvpsRoutes = require('./routes/event_rsvps');

const certificatesRoutes = require('./routes/certificates');


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: "MentorHub Demo",
        description: "MentorHub Demo 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/tutor_profiles', passport.authenticate('jwt', {session: false}), tutor_profilesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

db.sequelize.sync().then(function () {
  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });
});

module.exports = app;
