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

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

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

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

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

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

const staffRoutes = require('./routes/staff');

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

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

const class_subjectsRoutes = require('./routes/class_subjects');

const timetablesRoutes = require('./routes/timetables');

const timetable_periodsRoutes = require('./routes/timetable_periods');

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

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

const fee_plansRoutes = require('./routes/fee_plans');

const invoicesRoutes = require('./routes/invoices');

const paymentsRoutes = require('./routes/payments');

const assessmentsRoutes = require('./routes/assessments');

const assessment_resultsRoutes = require('./routes/assessment_results');

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

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

const documentsRoutes = require('./routes/documents');


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 Chain Manager",
        description: "School Chain Manager 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/campuses', passport.authenticate('jwt', {session: false}), campusesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
