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

const education_levelsRoutes = require('./routes/education_levels');

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

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

const parent_student_linksRoutes = require('./routes/parent_student_links');

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

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

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

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

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

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

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

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

const exam_categoriesRoutes = require('./routes/exam_categories');

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

const exam_questionsRoutes = require('./routes/exam_questions');

const exam_question_choicesRoutes = require('./routes/exam_question_choices');

const exam_attemptsRoutes = require('./routes/exam_attempts');

const exam_answersRoutes = require('./routes/exam_answers');

const fee_definitionsRoutes = require('./routes/fee_definitions');

const billing_itemsRoutes = require('./routes/billing_items');

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

const notification_logsRoutes = require('./routes/notification_logs');


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: "Sistem Sekolah Indonesia",
        description: "Sistem Sekolah Indonesia 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/academic_years', passport.authenticate('jwt', {session: false}), academic_yearsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

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

module.exports = app;
