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

const languagesRoutes = require('./routes/languages');

const user_languagesRoutes = require('./routes/user_languages');

const interestsRoutes = require('./routes/interests');

const user_interestsRoutes = require('./routes/user_interests');

const discovery_preferencesRoutes = require('./routes/discovery_preferences');

const swipesRoutes = require('./routes/swipes');

const matchesRoutes = require('./routes/matches');

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

const chat_eventsRoutes = require('./routes/chat_events');

const blocksRoutes = require('./routes/blocks');

const reportsRoutes = require('./routes/reports');

const report_attachmentsRoutes = require('./routes/report_attachments');

const notificationsRoutes = require('./routes/notifications');

const daily_sparksRoutes = require('./routes/daily_sparks');

const daily_spark_recommendationsRoutes = require('./routes/daily_spark_recommendations');

const premium_plansRoutes = require('./routes/premium_plans');

const subscriptionsRoutes = require('./routes/subscriptions');

const user_settingsRoutes = require('./routes/user_settings');

const content_moderation_itemsRoutes = require('./routes/content_moderation_items');

const admin_usersRoutes = require('./routes/admin_users');

const analytics_eventsRoutes = require('./routes/analytics_events');


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: "Crush247 Dating App",
        description: "Crush247 Dating 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/user_photos', passport.authenticate('jwt', {session: false}), user_photosRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
