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

const fan_profilesRoutes = require('./routes/fan_profiles');

const followsRoutes = require('./routes/follows');

const theme_profilesRoutes = require('./routes/theme_profiles');

const profile_stylesRoutes = require('./routes/profile_styles');

const discovery_itemsRoutes = require('./routes/discovery_items');

const streamsRoutes = require('./routes/streams');

const videosRoutes = require('./routes/videos');

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

const playlistsRoutes = require('./routes/playlists');

const playlist_itemsRoutes = require('./routes/playlist_items');

const tip_pagesRoutes = require('./routes/tip_pages');

const tipsRoutes = require('./routes/tips');

const alert_profilesRoutes = require('./routes/alert_profiles');

const alertsRoutes = require('./routes/alerts');

const overlay_profilesRoutes = require('./routes/overlay_profiles');

const widget_catalog_itemsRoutes = require('./routes/widget_catalog_items');

const overlay_widgetsRoutes = require('./routes/overlay_widgets');

const merch_storesRoutes = require('./routes/merch_stores');

const productsRoutes = require('./routes/products');

const product_variantsRoutes = require('./routes/product_variants');

const ordersRoutes = require('./routes/orders');

const order_itemsRoutes = require('./routes/order_items');

const shipping_profilesRoutes = require('./routes/shipping_profiles');

const private_mailboxesRoutes = require('./routes/private_mailboxes');

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

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

const demo_walletsRoutes = require('./routes/demo_wallets');

const wallet_transactionsRoutes = require('./routes/wallet_transactions');


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: "Xpansion Creator Platform",
        description: "Xpansion Creator 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/creator_profiles', passport.authenticate('jwt', {session: false}), creator_profilesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
