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

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

const leadsRoutes = require('./routes/leads');

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

const quote_line_itemsRoutes = require('./routes/quote_line_items');

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

const project_milestonesRoutes = require('./routes/project_milestones');

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

const materialsRoutes = require('./routes/materials');

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

const inventory_locationsRoutes = require('./routes/inventory_locations');

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

const inventory_transactionsRoutes = require('./routes/inventory_transactions');

const bomsRoutes = require('./routes/boms');

const bom_itemsRoutes = require('./routes/bom_items');

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

const purchase_order_line_itemsRoutes = require('./routes/purchase_order_line_items');

const goods_receiptsRoutes = require('./routes/goods_receipts');

const work_ordersRoutes = require('./routes/work_orders');

const work_order_materialsRoutes = require('./routes/work_order_materials');

const deliveriesRoutes = require('./routes/deliveries');

const delivery_itemsRoutes = require('./routes/delivery_items');

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

const invoice_line_itemsRoutes = require('./routes/invoice_line_items');

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

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


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: "Westernframers ERP",
        description: "Westernframers ERP 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/customers', passport.authenticate('jwt', {session: false}), customersRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

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

module.exports = app;
