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

const workspace_membershipsRoutes = require('./routes/workspace_memberships');

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

const topicsRoutes = require('./routes/topics');

const pagesRoutes = require('./routes/pages');

const blocksRoutes = require('./routes/blocks');

const databasesRoutes = require('./routes/databases');

const database_entriesRoutes = require('./routes/database_entries');

const sourcesRoutes = require('./routes/sources');

const source_chunksRoutes = require('./routes/source_chunks');

const ai_jobsRoutes = require('./routes/ai_jobs');

const concept_mapsRoutes = require('./routes/concept_maps');

const study_guidesRoutes = require('./routes/study_guides');

const flashcard_decksRoutes = require('./routes/flashcard_decks');

const flashcardsRoutes = require('./routes/flashcards');

const spaced_repetition_statesRoutes = require('./routes/spaced_repetition_states');

const study_sessionsRoutes = require('./routes/study_sessions');

const review_eventsRoutes = require('./routes/review_events');

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

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

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

const tutor_conversationsRoutes = require('./routes/tutor_conversations');

const tutor_messagesRoutes = require('./routes/tutor_messages');

const study_plansRoutes = require('./routes/study_plans');

const study_plan_itemsRoutes = require('./routes/study_plan_items');

const dashboard_snapshotsRoutes = require('./routes/dashboard_snapshots');


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: "Study OS AI",
        description: "Study OS AI 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/workspaces', passport.authenticate('jwt', {session: false}), workspacesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
