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

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

const brandsRoutes = require('./routes/brands');

const brand_rate_cardsRoutes = require('./routes/brand_rate_cards');

const client_ordersRoutes = require('./routes/client_orders');

const clientsRoutes = require('./routes/clients');

const countriesRoutes = require('./routes/countries');

const default_activities_productsRoutes = require('./routes/default_activities_products');

const departmentsRoutes = require('./routes/departments');

const marketsRoutes = require('./routes/markets');

const outwork_line_itemsRoutes = require('./routes/outwork_line_items');

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

const saved_adaptationsRoutes = require('./routes/saved_adaptations');

const specs_databaseRoutes = require('./routes/specs_database');

const suppliersRoutes = require('./routes/suppliers');

const supporting_documentsRoutes = require('./routes/supporting_documents');

const tracking_categoriesRoutes = require('./routes/tracking_categories');

const ziflow_workflowsRoutes = require('./routes/ziflow_workflows');

const quotesRoutes = require('./routes/quotes');

const jobsRoutes = require('./routes/jobs');

const adbuilder_assetsRoutes = require('./routes/adbuilder_assets');

const client_damRoutes = require('./routes/client_dam');

const outworkRoutes = require('./routes/outwork');

const adbuilder_templatesRoutes = require('./routes/adbuilder_templates');

const campaignsRoutes = require('./routes/campaigns');

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

const blogsRoutes = require('./routes/blogs');

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

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

const postsRoutes = require('./routes/posts');

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

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

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

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: "Curious Demo",
        description: "Curious Demo 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.enable('trust proxy');

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
