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

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

const school_yearsRoutes = require('./routes/school_years');

const gradesRoutes = require('./routes/grades');

const streamsRoutes = require('./routes/streams');

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

const subject_offeringsRoutes = require('./routes/subject_offerings');

const staff_membersRoutes = require('./routes/staff_members');

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

const class_sectionsRoutes = require('./routes/class_sections');

const enrollmentsRoutes = require('./routes/enrollments');

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

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

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

const news_postsRoutes = require('./routes/news_posts');

const galleriesRoutes = require('./routes/galleries');

const study_materialsRoutes = require('./routes/study_materials');

const examsRoutes = require('./routes/exams');

const exam_resultsRoutes = require('./routes/exam_results');

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

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

const class_schedulesRoutes = require('./routes/class_schedules');

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

const assignment_submissionsRoutes = require('./routes/assignment_submissions');

const lesson_plansRoutes = require('./routes/lesson_plans');

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

const admission_applicationsRoutes = require('./routes/admission_applications');

const contact_messagesRoutes = require('./routes/contact_messages');

const alumniRoutes = require('./routes/alumni');

const school_statisticsRoutes = require('./routes/school_statistics');

const exam_performance_summariesRoutes = require('./routes/exam_performance_summaries');

const top_student_featuresRoutes = require('./routes/top_student_features');


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: "Limmu Gennet School Website",
        description: "Limmu Gennet School Website 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/school_settings', passport.authenticate('jwt', {session: false}), school_settingsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
