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

const languagesRoutes = require('./routes/languages');

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

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

const project_collaborationsRoutes = require('./routes/project_collaborations');

const songsRoutes = require('./routes/songs');

const song_metadataRoutes = require('./routes/song_metadata');

const assetsRoutes = require('./routes/assets');

const recording_sessionsRoutes = require('./routes/recording_sessions');

const tracksRoutes = require('./routes/tracks');

const arrangement_sectionsRoutes = require('./routes/arrangement_sections');

const generation_requestsRoutes = require('./routes/generation_requests');

const vocal_processing_presetsRoutes = require('./routes/vocal_processing_presets');

const mastering_presetsRoutes = require('./routes/mastering_presets');

const mix_sessionsRoutes = require('./routes/mix_sessions');

const mastering_sessionsRoutes = require('./routes/mastering_sessions');

const exportsRoutes = require('./routes/exports');

const cover_artworksRoutes = require('./routes/cover_artworks');

const marketplace_listingsRoutes = require('./routes/marketplace_listings');

const marketplace_ordersRoutes = require('./routes/marketplace_orders');
const studioRoutes = require('./routes/studio');


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: "SA AI Music Studio",
        description: "SA AI Music Studio 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/genres', passport.authenticate('jwt', {session: false}), genresRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
