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

const artist_profilesRoutes = require('./routes/artist_profiles');

const teamsRoutes = require('./routes/teams');

const team_membershipsRoutes = require('./routes/team_memberships');

const plansRoutes = require('./routes/plans');

const subscriptionsRoutes = require('./routes/subscriptions');

const distribution_platformsRoutes = require('./routes/distribution_platforms');

const genresRoutes = require('./routes/genres');

const releasesRoutes = require('./routes/releases');

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

const track_contributorsRoutes = require('./routes/track_contributors');

const release_deliveriesRoutes = require('./routes/release_deliveries');

const smart_linksRoutes = require('./routes/smart_links');

const smart_link_destinationsRoutes = require('./routes/smart_link_destinations');

const smart_link_clicksRoutes = require('./routes/smart_link_clicks');

const playlistsRoutes = require('./routes/playlists');

const pitch_requestsRoutes = require('./routes/pitch_requests');

const playlist_placementsRoutes = require('./routes/playlist_placements');

const royalty_reportsRoutes = require('./routes/royalty_reports');

const royalty_linesRoutes = require('./routes/royalty_lines');

const walletsRoutes = require('./routes/wallets');

const wallet_transactionsRoutes = require('./routes/wallet_transactions');

const payout_methodsRoutes = require('./routes/payout_methods');

const withdrawal_requestsRoutes = require('./routes/withdrawal_requests');

const tax_documentsRoutes = require('./routes/tax_documents');

const analytics_dailyRoutes = require('./routes/analytics_daily');

const notificationsRoutes = require('./routes/notifications');

const notification_preferencesRoutes = require('./routes/notification_preferences');

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

const dashboard_widgetsRoutes = require('./routes/dashboard_widgets');

const activity_eventsRoutes = require('./routes/activity_events');

const blog_postsRoutes = require('./routes/blog_posts');

const faq_itemsRoutes = require('./routes/faq_items');

const contact_messagesRoutes = require('./routes/contact_messages');

const referral_programsRoutes = require('./routes/referral_programs');

const referral_linksRoutes = require('./routes/referral_links');

const referral_conversionsRoutes = require('./routes/referral_conversions');


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: "СВЕМА — дистрибуция музыки",
        description: "СВЕМА — дистрибуция музыки 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/oauth_accounts', passport.authenticate('jwt', {session: false}), oauth_accountsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
