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

const organizationForAuthRoutes = require('./routes/organizationLogin');

const openaiRoutes = require('./routes/openai');

const contactFormRoutes = require('./routes/contactForm');

const usersRoutes = require('./routes/users');

const activity_logsRoutes = require('./routes/activity_logs');

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

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

const billsRoutes = require('./routes/bills');

const class_messagesRoutes = require('./routes/class_messages');

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

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

const exam_subjectsRoutes = require('./routes/exam_subjects');

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

const fee_paymentsRoutes = require('./routes/fee_payments');

const fee_structuresRoutes = require('./routes/fee_structures');

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

const login_logsRoutes = require('./routes/login_logs');

const marksRoutes = require('./routes/marks');

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

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

const period_settingsRoutes = require('./routes/period_settings');

const school_adminsRoutes = require('./routes/school_admins');

const student_attendanceRoutes = require('./routes/student_attendance');

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

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

const teacher_attendanceRoutes = require('./routes/teacher_attendance');

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

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

const rolesRoutes = require('./routes/roles');

const permissionsRoutes = require('./routes/permissions');

const schoolsRoutes = require('./routes/schools');

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: 'Nexus school management',
      description:
        'Nexus school management 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/activity_logs',
  passport.authenticate('jwt', { session: false }),
  activity_logsRoutes,
);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/contact-form', contactFormRoutes);

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

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;

db.sequelize.sync().then(function () {
  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });
});

module.exports = app;
