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

const referralsRoutes = require('./routes/referrals');

const coin_earning_rulesRoutes = require('./routes/coin_earning_rules');

const coin_codesRoutes = require('./routes/coin_codes');

const coin_code_redemptionsRoutes = require('./routes/coin_code_redemptions');

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

const coin_conversionsRoutes = require('./routes/coin_conversions');

const membership_plansRoutes = require('./routes/membership_plans');

const user_membershipsRoutes = require('./routes/user_memberships');

const shop_itemsRoutes = require('./routes/shop_items');

const item_redemptionsRoutes = require('./routes/item_redemptions');

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

const article_contentsRoutes = require('./routes/article_contents');

const comic_contentsRoutes = require('./routes/comic_contents');

const video_contentsRoutes = require('./routes/video_contents');

const game_contentsRoutes = require('./routes/game_contents');

const product_purchasesRoutes = require('./routes/product_purchases');

const content_consumptionsRoutes = require('./routes/content_consumptions');

const chat_roomsRoutes = require('./routes/chat_rooms');

const chat_membershipsRoutes = require('./routes/chat_memberships');

const chat_messagesRoutes = require('./routes/chat_messages');

const app_settingsRoutes = require('./routes/app_settings');

const admin_audit_logsRoutes = require('./routes/admin_audit_logs');


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: "Daily Doodle App",
        description: "Daily Doodle 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_sessions', passport.authenticate('jwt', {session: false}), user_sessionsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
