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

const grade_levelsRoutes = require('./routes/grade_levels');

const textbooksRoutes = require('./routes/textbooks');

const chaptersRoutes = require('./routes/chapters');

const curriculum_standardsRoutes = require('./routes/curriculum_standards');

const skillsRoutes = require('./routes/skills');

const question_banksRoutes = require('./routes/question_banks');

const questionsRoutes = require('./routes/questions');

const answer_choicesRoutes = require('./routes/answer_choices');

const testsRoutes = require('./routes/tests');

const test_sectionsRoutes = require('./routes/test_sections');

const test_itemsRoutes = require('./routes/test_items');

const test_versionsRoutes = require('./routes/test_versions');

const version_itemsRoutes = require('./routes/version_items');

const version_answer_ordersRoutes = require('./routes/version_answer_orders');

const exportsRoutes = require('./routes/exports');

const answer_keysRoutes = require('./routes/answer_keys');

const scoring_schemesRoutes = require('./routes/scoring_schemes');

const test_matricesRoutes = require('./routes/test_matrices');

const matrix_rowsRoutes = require('./routes/matrix_rows');

const collectionsRoutes = require('./routes/collections');

const ai_generation_jobsRoutes = require('./routes/ai_generation_jobs');


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: "App Preview",
        description: "App Preview 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/subjects', passport.authenticate('jwt', {session: false}), subjectsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
