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

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

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

const classroomsRoutes = require('./routes/classrooms');

const classroom_membershipsRoutes = require('./routes/classroom_memberships');

const teaching_assignmentsRoutes = require('./routes/teaching_assignments');

const homeworksRoutes = require('./routes/homeworks');

const homework_rubricsRoutes = require('./routes/homework_rubrics');

const homework_extensionsRoutes = require('./routes/homework_extensions');

const homework_submissionsRoutes = require('./routes/homework_submissions');

const submission_gradesRoutes = require('./routes/submission_grades');

const rubric_scoresRoutes = require('./routes/rubric_scores');

const gradebooksRoutes = require('./routes/gradebooks');

const gradebook_columnsRoutes = require('./routes/gradebook_columns');

const gradebook_entriesRoutes = require('./routes/gradebook_entries');

const adviser_reportsRoutes = require('./routes/adviser_reports');

const announcementsRoutes = require('./routes/announcements');

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

const account_applicationsRoutes = require('./routes/account_applications');

const guardiansRoutes = require('./routes/guardians');

const security_eventsRoutes = require('./routes/security_events');

const support_settingsRoutes = require('./routes/support_settings');

const feedback_itemsRoutes = require('./routes/feedback_items');

const eventsRoutes = require('./routes/events');

const ai_monitoring_rulesRoutes = require('./routes/ai_monitoring_rules');


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: "Homework & Grading Portal",
        description: "Homework & Grading Portal 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/schools', passport.authenticate('jwt', {session: false}), schoolsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
