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

const usersRoutes = require('./routes/users');

const rolesRoutes = require('./routes/roles');

const permissionsRoutes = require('./routes/permissions');

const refresh_tokensRoutes = require('./routes/refresh_tokens');

const categoriesRoutes = require('./routes/categories');

const locationsRoutes = require('./routes/locations');

const businessesRoutes = require('./routes/businesses');

const business_photosRoutes = require('./routes/business_photos');

const business_categoriesRoutes = require('./routes/business_categories');

const service_pricesRoutes = require('./routes/service_prices');

const business_badgesRoutes = require('./routes/business_badges');

const verification_submissionsRoutes = require('./routes/verification_submissions');

const verification_evidencesRoutes = require('./routes/verification_evidences');

const claim_requestsRoutes = require('./routes/claim_requests');

const leadsRoutes = require('./routes/leads');

const lead_photosRoutes = require('./routes/lead_photos');

const lead_matchesRoutes = require('./routes/lead_matches');

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

const lead_eventsRoutes = require('./routes/lead_events');

const reviewsRoutes = require('./routes/reviews');

const disputesRoutes = require('./routes/disputes');

const audit_logsRoutes = require('./routes/audit_logs');

const badge_rulesRoutes = require('./routes/badge_rules');

const trust_adjustmentsRoutes = require('./routes/trust_adjustments');


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: "Fix-It-Local",
        description: "Fix-It-Local 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());
 
const optionalAuth = (req, res, next) => {
    passport.authenticate('jwt', { session: false }, (err, user, info) => {
        if (user) {
            req.currentUser = user;
        }
        next();
    })(req, res, next);
};

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

app.use('/api/categories', optionalAuth, categoriesRoutes);

app.use('/api/locations', optionalAuth, locationsRoutes);

app.use('/api/businesses', optionalAuth, businessesRoutes);

app.use('/api/business_photos', optionalAuth, business_photosRoutes);

app.use('/api/business_categories', optionalAuth, business_categoriesRoutes);

app.use('/api/service_prices', optionalAuth, service_pricesRoutes);

app.use('/api/business_badges', optionalAuth, business_badgesRoutes);

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

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

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

app.use('/api/leads', optionalAuth, leadsRoutes);

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

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

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

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

app.use('/api/reviews', optionalAuth, reviewsRoutes);

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

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

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

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

app.use(
    '/api/openai',
    passport.authenticate('jwt', { session: false }),
    openaiRoutes,
);
app.use(
    '/api/ai',
    passport.authenticate('jwt', { session: false }),
    openaiRoutes,
);

app.use(
  '/api/dashboard',
  dashboardRoutes);

app.use(
  '/api/search',
  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;