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



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

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

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

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

const devicesRoutes = require('./routes/devices');

const repair_ordersRoutes = require('./routes/repair_orders');

const repair_servicesRoutes = require('./routes/repair_services');

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

const payment_methodsRoutes = require('./routes/payment_methods');

const paymentsRoutes = require('./routes/payments');

const invoicesRoutes = require('./routes/invoices');

const invoice_itemsRoutes = require('./routes/invoice_items');

const whatsapp_notificationsRoutes = require('./routes/whatsapp_notifications');

const ai_chat_sessionsRoutes = require('./routes/ai_chat_sessions');

const ai_chat_messagesRoutes = require('./routes/ai_chat_messages');

const qr_linksRoutes = require('./routes/qr_links');
const repairIntakeRoutes = require('./routes/repair_intake');


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: "Floresoftware Ideas",
        description: "Floresoftware Ideas 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/customers', passport.authenticate('jwt', {session: false}), customersRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/repair-intake', passport.authenticate('jwt', { session: false }), repairIntakeRoutes);

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;
