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

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

const workspacesRoutes = require('./routes/workspaces');

const llm_providersRoutes = require('./routes/llm_providers');

const llm_modelsRoutes = require('./routes/llm_models');

const llm_api_keysRoutes = require('./routes/llm_api_keys');

const key_rotation_policiesRoutes = require('./routes/key_rotation_policies');

const prompt_templatesRoutes = require('./routes/prompt_templates');

const chatsRoutes = require('./routes/chats');

const chat_messagesRoutes = require('./routes/chat_messages');

const encryption_sessionsRoutes = require('./routes/encryption_sessions');

const code_repositoriesRoutes = require('./routes/code_repositories');

const code_filesRoutes = require('./routes/code_files');

const code_change_setsRoutes = require('./routes/code_change_sets');

const code_patchesRoutes = require('./routes/code_patches');

const build_jobsRoutes = require('./routes/build_jobs');

const build_pipelinesRoutes = require('./routes/build_pipelines');

const build_artifactsRoutes = require('./routes/build_artifacts');

const web_search_queriesRoutes = require('./routes/web_search_queries');

const web_search_resultsRoutes = require('./routes/web_search_results');

const system_health_checksRoutes = require('./routes/system_health_checks');

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: "AI Coding Assistant Suite",
        description: "AI Coding Assistant Suite 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/organization_memberships', passport.authenticate('jwt', {session: false}), organization_membershipsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });

module.exports = app;
