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

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

const role_assignmentsRoutes = require('./routes/role_assignments');

const approval_workflowsRoutes = require('./routes/approval_workflows');

const approval_stepsRoutes = require('./routes/approval_steps');

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

const approval_decisionsRoutes = require('./routes/approval_decisions');

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

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

const suppliersRoutes = require('./routes/suppliers');

const uomsRoutes = require('./routes/uoms');

const item_categoriesRoutes = require('./routes/item_categories');

const itemsRoutes = require('./routes/items');

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

const locationsRoutes = require('./routes/locations');

const lotsRoutes = require('./routes/lots');

const serial_numbersRoutes = require('./routes/serial_numbers');

const inventory_transfersRoutes = require('./routes/inventory_transfers');

const inventory_transfer_linesRoutes = require('./routes/inventory_transfer_lines');

const stock_movementsRoutes = require('./routes/stock_movements');

const quotationsRoutes = require('./routes/quotations');

const quotation_linesRoutes = require('./routes/quotation_lines');

const sales_ordersRoutes = require('./routes/sales_orders');

const sales_order_linesRoutes = require('./routes/sales_order_lines');

const sales_allocationsRoutes = require('./routes/sales_allocations');

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

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

const customer_returnsRoutes = require('./routes/customer_returns');

const customer_return_linesRoutes = require('./routes/customer_return_lines');

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

const purchase_order_linesRoutes = require('./routes/purchase_order_lines');

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

const receipt_linesRoutes = require('./routes/receipt_lines');

const vendor_billsRoutes = require('./routes/vendor_bills');

const vendor_bill_linesRoutes = require('./routes/vendor_bill_lines');

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

const fiscal_periodsRoutes = require('./routes/fiscal_periods');

const journal_entriesRoutes = require('./routes/journal_entries');

const journal_linesRoutes = require('./routes/journal_lines');

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

const tax_ratesRoutes = require('./routes/tax_rates');

const webhooksRoutes = require('./routes/webhooks');

const webhook_subscriptionsRoutes = require('./routes/webhook_subscriptions');

const webhook_deliveriesRoutes = require('./routes/webhook_deliveries');

const email_notificationsRoutes = require('./routes/email_notifications');

const csv_import_jobsRoutes = require('./routes/csv_import_jobs');

const reportsRoutes = require('./routes/reports');

const dashboardsRoutes = require('./routes/dashboards');

const dashboard_widgetsRoutes = require('./routes/dashboard_widgets');


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: "Multitenant ERP Suite",
        description: "Multitenant ERP 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/tenants', passport.authenticate('jwt', {session: false}), tenantsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
