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

const openaiRoutes = require('./routes/openai');



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

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

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

const pagesRoutes = require('./routes/pages');

const cta_buttonsRoutes = require('./routes/cta_buttons');

const feature_highlightsRoutes = require('./routes/feature_highlights');

const galleriesRoutes = require('./routes/galleries');

const gallery_itemsRoutes = require('./routes/gallery_items');

const coffee_regionsRoutes = require('./routes/coffee_regions');

const coffee_lotsRoutes = require('./routes/coffee_lots');

const quality_processesRoutes = require('./routes/quality_processes');

const process_stepsRoutes = require('./routes/process_steps');

const quality_metricsRoutes = require('./routes/quality_metrics');

const export_service_itemsRoutes = require('./routes/export_service_items');

const sustainability_initiativesRoutes = require('./routes/sustainability_initiatives');

const testimonialsRoutes = require('./routes/testimonials');

const newsletter_subscribersRoutes = require('./routes/newsletter_subscribers');

const inquiriesRoutes = require('./routes/inquiries');

const contact_locationsRoutes = require('./routes/contact_locations');

const site_settingsRoutes = require('./routes/site_settings');


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: "Alem Desta Coffee Export Site",
        description: "Alem Desta Coffee Export Site 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.use('/api/contact-form', contactFormRoutes);
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/pages', passport.authenticate('jwt', {session: false}), pagesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
