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

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



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

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

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

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

const company_locationsRoutes = require('./routes/company_locations');

const company_contactsRoutes = require('./routes/company_contacts');

const company_bank_accountsRoutes = require('./routes/company_bank_accounts');

const company_permitsRoutes = require('./routes/company_permits');

const company_insurancesRoutes = require('./routes/company_insurances');

const company_documentsRoutes = require('./routes/company_documents');

const company_document_versionsRoutes = require('./routes/company_document_versions');

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

const employee_assignmentsRoutes = require('./routes/employee_assignments');

const employee_hr_recordsRoutes = require('./routes/employee_hr_records');

const driver_profilesRoutes = require('./routes/driver_profiles');

const driver_compliancesRoutes = require('./routes/driver_compliances');

const incidentsRoutes = require('./routes/incidents');

const documentsRoutes = require('./routes/documents');

const document_versionsRoutes = require('./routes/document_versions');

const document_retention_policiesRoutes = require('./routes/document_retention_policies');

const customersRoutes = require('./routes/customers');

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

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

const trailersRoutes = require('./routes/trailers');

const vehicle_trailer_linksRoutes = require('./routes/vehicle_trailer_links');

const vehicle_inspectionsRoutes = require('./routes/vehicle_inspections');

const vehicle_maintenancesRoutes = require('./routes/vehicle_maintenances');

const vehicle_insurancesRoutes = require('./routes/vehicle_insurances');

const vehicle_documentsRoutes = require('./routes/vehicle_documents');

const vehicle_document_versionsRoutes = require('./routes/vehicle_document_versions');

const driver_vehicle_assignmentsRoutes = require('./routes/driver_vehicle_assignments');

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

const loadsRoutes = require('./routes/loads');

const load_stopsRoutes = require('./routes/load_stops');

const tripsRoutes = require('./routes/trips');

const trip_loadsRoutes = require('./routes/trip_loads');

const pod_filesRoutes = require('./routes/pod_files');

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

const invoice_linesRoutes = require('./routes/invoice_lines');

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

const cost_itemsRoutes = require('./routes/cost_items');

const cost_filesRoutes = require('./routes/cost_files');

const fuel_entriesRoutes = require('./routes/fuel_entries');

const toll_entriesRoutes = require('./routes/toll_entries');


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: "Fleet & HR Logistics Suite",
        description: "Fleet & HR Logistics Suite 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/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/company_locations', passport.authenticate('jwt', {session: false}), company_locationsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  
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;
