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

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

const extensionsRoutes = require('./routes/extensions');

const surveysRoutes = require('./routes/surveys');

const fill_sessionsRoutes = require('./routes/fill_sessions');

const request_queueRoutes = require('./routes/request_queue');

const connection_logsRoutes = require('./routes/connection_logs');

const profilesRoutes = require('./routes/profiles');

const settingsRoutes = require('./routes/settings');


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 App Draft",
        description: "AI 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');

// Mock Auth Middleware for Extension (Single User Mode)
const mockAuthMiddleware = async (req, res, next) => {
  try {
    const user = await db.users.findOne();
    if (user) {
      req.currentUser = user;
    }
    next();
  } catch (error) {
    console.error("MockAuth Error:", error);
    next(error);
  }
};


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

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

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

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

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

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

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

app.use('/api/profiles', mockAuthMiddleware, profilesRoutes);

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

app.use(
    '/api/openai',
    mockAuthMiddleware,
    openaiRoutes,
);
app.use(
    '/api/ai',
    mockAuthMiddleware,
    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;