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

const import_sourcesRoutes = require('./routes/import_sources');

const file_uploadsRoutes = require('./routes/file_uploads');

const import_jobsRoutes = require('./routes/import_jobs');

const import_mappingsRoutes = require('./routes/import_mappings');

const mapping_rulesRoutes = require('./routes/mapping_rules');

const validation_rule_setsRoutes = require('./routes/validation_rule_sets');

const validation_rulesRoutes = require('./routes/validation_rules');

const import_row_resultsRoutes = require('./routes/import_row_results');

const import_issuesRoutes = require('./routes/import_issues');

const import_templatesRoutes = require('./routes/import_templates');

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

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

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

const availability_recordsRoutes = require('./routes/availability_records');

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: "ERP Import Validator",
        description: "ERP Import Validator 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/data_entities', passport.authenticate('jwt', {session: false}), data_entitiesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

db.sequelize.sync().then(function () {
  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });
});

module.exports = app;
