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

const campusesRoutes = require('./routes/campuses');

const academic_yearsRoutes = require('./routes/academic_years');

const termsRoutes = require('./routes/terms');

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

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

const roomsRoutes = require('./routes/rooms');

const studentsRoutes = require('./routes/students');

const parentsRoutes = require('./routes/parents');

const student_parent_linksRoutes = require('./routes/student_parent_links');

const teachersRoutes = require('./routes/teachers');

const classesRoutes = require('./routes/classes');

const class_enrollmentsRoutes = require('./routes/class_enrollments');

const course_sectionsRoutes = require('./routes/course_sections');

const timetable_entriesRoutes = require('./routes/timetable_entries');

const attendance_sessionsRoutes = require('./routes/attendance_sessions');

const attendance_recordsRoutes = require('./routes/attendance_records');

const assignmentsRoutes = require('./routes/assignments');

const submissionsRoutes = require('./routes/submissions');

const grade_itemsRoutes = require('./routes/grade_items');

const grade_recordsRoutes = require('./routes/grade_records');

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

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

const message_recipientsRoutes = require('./routes/message_recipients');

const eventsRoutes = require('./routes/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: "School Portal",
        description: "School 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/campuses', passport.authenticate('jwt', {session: false}), campusesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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