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

const membershipsRoutes = require('./routes/memberships');

const organization_settingsRoutes = require('./routes/organization_settings');

const tax_codesRoutes = require('./routes/tax_codes');

const contactsRoutes = require('./routes/contacts');

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

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

const inventory_itemsRoutes = require('./routes/inventory_items');

const quotesRoutes = require('./routes/quotes');

const quote_linesRoutes = require('./routes/quote_lines');

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

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

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

const receiptsRoutes = require('./routes/receipts');

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

const approval_requestsRoutes = require('./routes/approval_requests');

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

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

const time_entriesRoutes = require('./routes/time_entries');

const efris_connectionsRoutes = require('./routes/efris_connections');

const efris_submissionsRoutes = require('./routes/efris_submissions');

const audit_eventsRoutes = require('./routes/audit_events');


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: "EFRIS Accounting Suite",
        description: "EFRIS Accounting 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/organizations', passport.authenticate('jwt', {session: false}), organizationsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
