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

const brand_voice_profilesRoutes = require('./routes/brand_voice_profiles');

const brain_profilesRoutes = require('./routes/brain_profiles');

const skill_modulesRoutes = require('./routes/skill_modules');

const six_hat_sessionsRoutes = require('./routes/six_hat_sessions');

const knowledge_sourcesRoutes = require('./routes/knowledge_sources');

const knowledge_documentsRoutes = require('./routes/knowledge_documents');

const knowledge_chunksRoutes = require('./routes/knowledge_chunks');

const knowledge_nodesRoutes = require('./routes/knowledge_nodes');

const campaignsRoutes = require('./routes/campaigns');

const campaign_brain_configsRoutes = require('./routes/campaign_brain_configs');

const safety_policiesRoutes = require('./routes/safety_policies');

const audit_eventsRoutes = require('./routes/audit_events');

const ad_projectsRoutes = require('./routes/ad_projects');

const ad_creativesRoutes = require('./routes/ad_creatives');

const generation_runsRoutes = require('./routes/generation_runs');

const generation_outputsRoutes = require('./routes/generation_outputs');

const output_citationsRoutes = require('./routes/output_citations');

const feedback_entriesRoutes = require('./routes/feedback_entries');

const learning_signalsRoutes = require('./routes/learning_signals');

const platform_metricsRoutes = require('./routes/platform_metrics');

const sandbox_scenariosRoutes = require('./routes/sandbox_scenarios');

const refresh_jobsRoutes = require('./routes/refresh_jobs');

const approval_reviewsRoutes = require('./routes/approval_reviews');


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: "Ultimate Marketing Designer AI",
        description: "Ultimate Marketing Designer AI 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/brands', passport.authenticate('jwt', {session: false}), brandsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
