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

const contact_locationsRoutes = require('./routes/contact_locations');

const social_linksRoutes = require('./routes/social_links');

const hero_slidesRoutes = require('./routes/hero_slides');

const stone_categoriesRoutes = require('./routes/stone_categories');

const stone_colorsRoutes = require('./routes/stone_colors');

const finishesRoutes = require('./routes/finishes');

const applicationsRoutes = require('./routes/applications');

const stonesRoutes = require('./routes/stones');

const stone_variantsRoutes = require('./routes/stone_variants');

const stone_3d_assetsRoutes = require('./routes/stone_3d_assets');

const servicesRoutes = require('./routes/services');

const technologiesRoutes = require('./routes/technologies');

const service_technologiesRoutes = require('./routes/service_technologies');

const projectsRoutes = require('./routes/projects');

const project_mediaRoutes = require('./routes/project_media');

const team_membersRoutes = require('./routes/team_members');

const blog_categoriesRoutes = require('./routes/blog_categories');

const blog_postsRoutes = require('./routes/blog_posts');

const lead_requestsRoutes = require('./routes/lead_requests');

const quote_itemsRoutes = require('./routes/quote_items');

const inquiriesRoutes = require('./routes/inquiries');

const seo_pagesRoutes = require('./routes/seo_pages');

const media_libraryRoutes = require('./routes/media_library');


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: "Stone Factory Arabic Site",
        description: "Stone Factory Arabic Site 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/site_settings', passport.authenticate('jwt', {session: false}), site_settingsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

db.sequelize.sync().then(function () {
  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });
});

module.exports = app;
