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

const club_membershipsRoutes = require('./routes/club_memberships');

const playersRoutes = require('./routes/players');

const seed_votesRoutes = require('./routes/seed_votes');

const venuesRoutes = require('./routes/venues');

const leaguesRoutes = require('./routes/leagues');

const league_teamsRoutes = require('./routes/league_teams');

const league_team_playersRoutes = require('./routes/league_team_players');

const gamesRoutes = require('./routes/games');

const game_rsvpsRoutes = require('./routes/game_rsvps');

const game_guestsRoutes = require('./routes/game_guests');

const game_teamsRoutes = require('./routes/game_teams');

const game_team_assignmentsRoutes = require('./routes/game_team_assignments');

const game_attendancesRoutes = require('./routes/game_attendances');

const game_player_statsRoutes = require('./routes/game_player_stats');

const game_paymentsRoutes = require('./routes/game_payments');

const league_paymentsRoutes = require('./routes/league_payments');

const league_standingsRoutes = require('./routes/league_standings');

const league_finish_awardsRoutes = require('./routes/league_finish_awards');

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

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: "My Soccer Club",
        description: "My Soccer Club 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/clubs', passport.authenticate('jwt', {session: false}), clubsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
