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

const authorsRoutes = require('./routes/authors');

const genresRoutes = require('./routes/genres');

const booksRoutes = require('./routes/books');

const user_library_itemsRoutes = require('./routes/user_library_items');

const bookmarksRoutes = require('./routes/bookmarks');

const notesRoutes = require('./routes/notes');

const camera_scan_sessionsRoutes = require('./routes/camera_scan_sessions');

const coin_ledger_entriesRoutes = require('./routes/coin_ledger_entries');

const withdrawal_requestsRoutes = require('./routes/withdrawal_requests');

const payment_transactionsRoutes = require('./routes/payment_transactions');

const daily_login_rewardsRoutes = require('./routes/daily_login_rewards');

const reading_streaksRoutes = require('./routes/reading_streaks');

const achievement_definitionsRoutes = require('./routes/achievement_definitions');

const user_achievementsRoutes = require('./routes/user_achievements');

const rank_tiersRoutes = require('./routes/rank_tiers');

const user_ranksRoutes = require('./routes/user_ranks');

const challenge_definitionsRoutes = require('./routes/challenge_definitions');

const user_challengesRoutes = require('./routes/user_challenges');

const quiz_definitionsRoutes = require('./routes/quiz_definitions');

const quiz_questionsRoutes = require('./routes/quiz_questions');

const quiz_answer_choicesRoutes = require('./routes/quiz_answer_choices');

const quiz_attemptsRoutes = require('./routes/quiz_attempts');

const friendshipsRoutes = require('./routes/friendships');

const book_clubsRoutes = require('./routes/book_clubs');

const book_club_membershipsRoutes = require('./routes/book_club_memberships');

const club_chat_messagesRoutes = require('./routes/club_chat_messages');

const reading_circle_eventsRoutes = require('./routes/reading_circle_events');

const recommendation_eventsRoutes = require('./routes/recommendation_events');

const push_notificationsRoutes = require('./routes/push_notifications');

const fraud_flagsRoutes = require('./routes/fraud_flags');

const kyc_verificationsRoutes = require('./routes/kyc_verifications');

const user_uploadsRoutes = require('./routes/user_uploads');


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: "NOIR AI",
        description: "NOIR AI 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/publishers', passport.authenticate('jwt', {session: false}), publishersRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });

module.exports = app;
