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



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

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

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

const store_settingsRoutes = require('./routes/store_settings');

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

const categoriesRoutes = require('./routes/categories');

const brandsRoutes = require('./routes/brands');

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

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

const variant_optionsRoutes = require('./routes/variant_options');

const product_reviewsRoutes = require('./routes/product_reviews');

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

const order_addressesRoutes = require('./routes/order_addresses');

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

const shipmentsRoutes = require('./routes/shipments');

const couponsRoutes = require('./routes/coupons');

const coupon_redemptionsRoutes = require('./routes/coupon_redemptions');

const wishlist_itemsRoutes = require('./routes/wishlist_items');

const home_sectionsRoutes = require('./routes/home_sections');

const home_section_itemsRoutes = require('./routes/home_section_items');

const contact_messagesRoutes = require('./routes/contact_messages');

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

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


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: "Arabic Storefront CMS",
        description: "Arabic Storefront CMS 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/store_settings', passport.authenticate('jwt', {session: false}), store_settingsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
