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

const camp_sessionsRoutes = require('./routes/camp_sessions');

const age_groupsRoutes = require('./routes/age_groups');

const weekly_themesRoutes = require('./routes/weekly_themes');

const pricing_plansRoutes = require('./routes/pricing_plans');

const fee_rulesRoutes = require('./routes/fee_rules');

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

const campersRoutes = require('./routes/campers');

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

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

const waiver_documentsRoutes = require('./routes/waiver_documents');

const document_signaturesRoutes = require('./routes/document_signatures');

const field_trip_catalogRoutes = require('./routes/field_trip_catalog');

const field_trip_eventsRoutes = require('./routes/field_trip_events');

const trip_registrationsRoutes = require('./routes/trip_registrations');

const special_tripsRoutes = require('./routes/special_trips');

const end_of_summer_trip_optionsRoutes = require('./routes/end_of_summer_trip_options');

const end_of_summer_trip_selectionsRoutes = require('./routes/end_of_summer_trip_selections');

const activity_blocksRoutes = require('./routes/activity_blocks');

const curriculum_subjectsRoutes = require('./routes/curriculum_subjects');

const staff_assignmentsRoutes = require('./routes/staff_assignments');

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


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: "Relentless Generation Camp App",
        description: "Relentless Generation Camp App 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/campuses', passport.authenticate('jwt', {session: false}), campusesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
