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

const claimsRoutes = require('./routes/claims');

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

const company_profilesRoutes = require('./routes/company_profiles');

const driversRoutes = require('./routes/drivers');

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

const guaranteesRoutes = require('./routes/guarantees');

const infractionsRoutes = require('./routes/infractions');

const invoices_saasRoutes = require('./routes/invoices_saas');

const maintenanceRoutes = require('./routes/maintenance');

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

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

const reservationsRoutes = require('./routes/reservations');

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

const tenantsRoutes = require('./routes/tenants');

const vehicle_conditionsRoutes = require('./routes/vehicle_conditions');

const vehiclesRoutes = require('./routes/vehicles');

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

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

const agencesRoutes = require('./routes/agences');

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: 'Car zone',
      description:
        'Car zone 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/claims',
  passport.authenticate('jwt', { session: false }),
  claimsRoutes,
);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
