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

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

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

const agreementsRoutes = require('./routes/agreements');

const recurring_invoice_templatesRoutes = require('./routes/recurring_invoice_templates');

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

const chart_of_accountsRoutes = require('./routes/chart_of_accounts');

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

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

const payment_allocationsRoutes = require('./routes/payment_allocations');

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

const vehicle_expensesRoutes = require('./routes/vehicle_expenses');

const driver_expensesRoutes = require('./routes/driver_expenses');

const billsRoutes = require('./routes/bills');

const bill_linesRoutes = require('./routes/bill_lines');

const bill_paymentsRoutes = require('./routes/bill_payments');

const ledger_entriesRoutes = require('./routes/ledger_entries');

const loan_schedulesRoutes = require('./routes/loan_schedules');

const vehicle_complianceRoutes = require('./routes/vehicle_compliance');

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

const audit_logsRoutes = require('./routes/audit_logs');


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 Accounting SaaS",
        description: "Fleet Accounting SaaS 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/drivers', passport.authenticate('jwt', {session: false}), driversRoutes);

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

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

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

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

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

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/payment_allocations', passport.authenticate('jwt', {session: false}), payment_allocationsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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);

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;

  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });

module.exports = app;
