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

const workspace_membershipsRoutes = require('./routes/workspace_memberships');

const ai_modelsRoutes = require('./routes/ai_models');

const ai_agentsRoutes = require('./routes/ai_agents');

const agent_skillsRoutes = require('./routes/agent_skills');

const agent_skill_assignmentsRoutes = require('./routes/agent_skill_assignments');

const conversationsRoutes = require('./routes/conversations');

const messagesRoutes = require('./routes/messages');

const message_attachmentsRoutes = require('./routes/message_attachments');

const code_snippetsRoutes = require('./routes/code_snippets');

const executionsRoutes = require('./routes/executions');

const debug_sessionsRoutes = require('./routes/debug_sessions');

const debug_fixesRoutes = require('./routes/debug_fixes');

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

const project_filesRoutes = require('./routes/project_files');

const previewsRoutes = require('./routes/previews');

const tool_integrationsRoutes = require('./routes/tool_integrations');

const api_keysRoutes = require('./routes/api_keys');

const usage_eventsRoutes = require('./routes/usage_events');

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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);

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;
