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

const tenant_locationsRoutes = require('./routes/tenant_locations');

const pondsRoutes = require('./routes/ponds');

const speciesRoutes = require('./routes/species');

const batchesRoutes = require('./routes/batches');

const feed_productsRoutes = require('./routes/feed_products');

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

const inventory_movementsRoutes = require('./routes/inventory_movements');

const feeding_logsRoutes = require('./routes/feeding_logs');

const water_quality_logsRoutes = require('./routes/water_quality_logs');

const health_eventsRoutes = require('./routes/health_events');

const harvestsRoutes = require('./routes/harvests');

const marketplace_listingsRoutes = require('./routes/marketplace_listings');

const ordersRoutes = require('./routes/orders');

const order_itemsRoutes = require('./routes/order_items');

const payment_transactionsRoutes = require('./routes/payment_transactions');

const shipment_updatesRoutes = require('./routes/shipment_updates');

const investmentsRoutes = require('./routes/investments');

const api_keysRoutes = require('./routes/api_keys');

const webhook_endpointsRoutes = require('./routes/webhook_endpoints');

const webhook_deliveriesRoutes = require('./routes/webhook_deliveries');

const email_notificationsRoutes = require('./routes/email_notifications');

const audit_logsRoutes = require('./routes/audit_logs');

const csv_jobsRoutes = require('./routes/csv_jobs');


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: "Aquaculture Ops CRUD",
        description: "Aquaculture Ops CRUD 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/user_memberships', passport.authenticate('jwt', {session: false}), user_membershipsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
