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

const organizationForAuthRoutes = require('./routes/organizationLogin');

const openaiRoutes = require('./routes/openai');

const contactFormRoutes = require('./routes/contactForm');

const usersRoutes = require('./routes/users');

const analytics_dailyRoutes = require('./routes/analytics_daily');

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

const audit_logsRoutes = require('./routes/audit_logs');

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

const button_linksRoutes = require('./routes/button_links');

const domain_mappingsRoutes = require('./routes/domain_mappings');

const email_logsRoutes = require('./routes/email_logs');

const feature_flagsRoutes = require('./routes/feature_flags');

const flagsRoutes = require('./routes/flags');

const media_assetsRoutes = require('./routes/media_assets');

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

const plansRoutes = require('./routes/plans');

const profile_pagesRoutes = require('./routes/profile_pages');

const social_linksRoutes = require('./routes/social_links');

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

const templatesRoutes = require('./routes/templates');

const rolesRoutes = require('./routes/roles');

const permissionsRoutes = require('./routes/permissions');

const organizationsRoutes = require('./routes/organizations');

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: 'KevinHall',
      description:
        'KevinHall 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/analytics_daily',
  passport.authenticate('jwt', { session: false }),
  analytics_dailyRoutes,
);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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/openai',
  passport.authenticate('jwt', { session: false }),
  openaiRoutes,
);

app.use('/api/contact-form', contactFormRoutes);

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

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;
