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

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

const branchesRoutes = require('./routes/branches');

const calendarsRoutes = require('./routes/calendars');

const client_statusRoutes = require('./routes/client_status');

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

const communesRoutes = require('./routes/communes');

const depositsRoutes = require('./routes/deposits');

const districtsRoutes = require('./routes/districts');

const document_typeRoutes = require('./routes/document_type');

const expense_itemsRoutes = require('./routes/expense_items');

const expense_typesRoutes = require('./routes/expense_types');

const group_menusRoutes = require('./routes/group_menus');

const guarantorRoutes = require('./routes/guarantor');

const interest_ratesRoutes = require('./routes/interest_rates');

const loan_statusRoutes = require('./routes/loan_status');

const loan_typesRoutes = require('./routes/loan_types');

const loansRoutes = require('./routes/loans');

const membersRoutes = require('./routes/members');

const menusRoutes = require('./routes/menus');

const payment_revenuesRoutes = require('./routes/payment_revenues');

const payment_statusRoutes = require('./routes/payment_status');

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

const paymentsRoutes = require('./routes/payments');

const provincesRoutes = require('./routes/provinces');

const sexesRoutes = require('./routes/sexes');

const shareholdersRoutes = require('./routes/shareholders');

const staff_statusRoutes = require('./routes/staff_status');

const staffsRoutes = require('./routes/staffs');

const urlsRoutes = require('./routes/urls');

const user_has_menuRoutes = require('./routes/user_has_menu');

const user_type_urlsRoutes = require('./routes/user_type_urls');

const user_typesRoutes = require('./routes/user_types');

const villagesRoutes = require('./routes/villages');

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: "meng-leap-cash",
        description: "meng-leap-cash 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/users', passport.authenticate('jwt', {session: false}), usersRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
