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



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

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

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

const organizationsRoutes = require('./routes/organizations');

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

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

const pipelinesRoutes = require('./routes/pipelines');

const pipeline_stagesRoutes = require('./routes/pipeline_stages');

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

const dealsRoutes = require('./routes/deals');

const activitiesRoutes = require('./routes/activities');

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

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

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

const machinesRoutes = require('./routes/machines');

const production_ordersRoutes = require('./routes/production_orders');

const production_operationsRoutes = require('./routes/production_operations');

const quality_inspectionsRoutes = require('./routes/quality_inspections');

const nonconformancesRoutes = require('./routes/nonconformances');

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

const venuesRoutes = require('./routes/venues');

const eventsRoutes = require('./routes/events');

const event_tasksRoutes = require('./routes/event_tasks');

const event_guestsRoutes = require('./routes/event_guests');

const event_schedule_itemsRoutes = require('./routes/event_schedule_items');

const budget_itemsRoutes = require('./routes/budget_items');


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: "DakikTabela Ops Suite",
        description: "DakikTabela Ops 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/companies', passport.authenticate('jwt', {session: false}), companiesRoutes);

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

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

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

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

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

app.use('/api/activities', passport.authenticate('jwt', {session: false}), activitiesRoutes);
app.use('/api/sales-hub', passport.authenticate('jwt', {session: false}), salesHubRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
