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

const role_permissionsRoutes = require('./routes/role_permissions');

const tenant_membershipsRoutes = require('./routes/tenant_memberships');

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

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

const product_variantsRoutes = require('./routes/product_variants');

const tax_ratesRoutes = require('./routes/tax_rates');

const discountsRoutes = require('./routes/discounts');

const registersRoutes = require('./routes/registers');

const shiftsRoutes = require('./routes/shifts');

const cartsRoutes = require('./routes/carts');

const cart_itemsRoutes = require('./routes/cart_items');

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

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

const payment_intentsRoutes = require('./routes/payment_intents');

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

const refundsRoutes = require('./routes/refunds');

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

const inventory_adjustmentsRoutes = require('./routes/inventory_adjustments');

const partnersRoutes = require('./routes/partners');

const tenant_partnershipsRoutes = require('./routes/tenant_partnerships');

const payoutsRoutes = require('./routes/payouts');

const helcim_configurationsRoutes = require('./routes/helcim_configurations');

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

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: "App Preview",
        description: "App Preview 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/locations', passport.authenticate('jwt', {session: false}), locationsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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_intents', passport.authenticate('jwt', {session: false}), payment_intentsRoutes);

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

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

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

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

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

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

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

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

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

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;
