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

const role_permissionsRoutes = require('./routes/role_permissions');

const membershipsRoutes = require('./routes/memberships');

const eventsRoutes = require('./routes/events');

const albumsRoutes = require('./routes/albums');

const album_collaboratorsRoutes = require('./routes/album_collaborators');

const access_rulesRoutes = require('./routes/access_rules');

const media_itemsRoutes = require('./routes/media_items');

const storage_bucketsRoutes = require('./routes/storage_buckets');

const storage_objectsRoutes = require('./routes/storage_objects');

const upload_sessionsRoutes = require('./routes/upload_sessions');

const upload_filesRoutes = require('./routes/upload_files');

const tagsRoutes = require('./routes/tags');

const media_ai_tagsRoutes = require('./routes/media_ai_tags');

const media_user_tagsRoutes = require('./routes/media_user_tags');

const likesRoutes = require('./routes/likes');

const favouritesRoutes = require('./routes/favourites');

const commentsRoutes = require('./routes/comments');

const mentionsRoutes = require('./routes/mentions');

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

const notification_preferencesRoutes = require('./routes/notification_preferences');

const sharesRoutes = require('./routes/shares');

const download_jobsRoutes = require('./routes/download_jobs');

const watermark_profilesRoutes = require('./routes/watermark_profiles');

const ai_modelsRoutes = require('./routes/ai_models');

const ai_embeddingsRoutes = require('./routes/ai_embeddings');

const face_detectionsRoutes = require('./routes/face_detections');

const selfie_referencesRoutes = require('./routes/selfie_references');

const face_matchesRoutes = require('./routes/face_matches');

const ai_captionsRoutes = require('./routes/ai_captions');

const moderation_flagsRoutes = require('./routes/moderation_flags');

const storiesRoutes = require('./routes/stories');

const story_itemsRoutes = require('./routes/story_items');

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

const oauth_accountsRoutes = require('./routes/oauth_accounts');


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: "Event Media Platform",
        description: "Event Media Platform 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/organizations', passport.authenticate('jwt', {session: false}), organizationsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

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

module.exports = app;
