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

const trialsRoutes = require('./routes/trials');

const trial_sitesRoutes = require('./routes/trial_sites');

const varietiesRoutes = require('./routes/varieties');

const trial_entriesRoutes = require('./routes/trial_entries');

const plotsRoutes = require('./routes/plots');

const plantsRoutes = require('./routes/plants');

const observation_eventsRoutes = require('./routes/observation_events');

const traitsRoutes = require('./routes/traits');

const observationsRoutes = require('./routes/observations');

const media_assetsRoutes = require('./routes/media_assets');

const report_templatesRoutes = require('./routes/report_templates');

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

const api_clientsRoutes = require('./routes/api_clients');


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: "Greenhouse Trials Tracker",
        description: "Greenhouse Trials Tracker 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/farms', passport.authenticate('jwt', {session: false}), farmsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
