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

const employeesRoutes = require('./routes/employees');

const financial_accountsRoutes = require('./routes/financial_accounts');

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

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

const projectsRoutes = require('./routes/projects');

const purchase_ordersRoutes = require('./routes/purchase_orders');

const tasksRoutes = require('./routes/tasks');

const transactionsRoutes = require('./routes/transactions');

const vendorsRoutes = require('./routes/vendors');

const invoicesRoutes = require('./routes/invoices');

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

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

const contractsRoutes = require('./routes/contracts');

const shipmentsRoutes = require('./routes/shipments');

const warehousesRoutes = require('./routes/warehouses');

const assetsRoutes = require('./routes/assets');

const payrollsRoutes = require('./routes/payrolls');

const attendanceRoutes = require('./routes/attendance');

const leave_requestsRoutes = require('./routes/leave_requests');

const recruitmentRoutes = require('./routes/recruitment');

const budgetsRoutes = require('./routes/budgets');

const taxesRoutes = require('./routes/taxes');

const expensesRoutes = require('./routes/expenses');

const revenuesRoutes = require('./routes/revenues');

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

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

const companiesRoutes = require('./routes/companies');

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      version: '1.0.0',
      title: 'allinoneerp',
      description:
        'allinoneerp Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.',
    },
    servers: [
      {
        url: 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 = 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/customers',
  passport.authenticate('jwt', { session: false }),
  customersRoutes,
);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
