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

const service_categoriesRoutes = require('./routes/service_categories');

const service_listingsRoutes = require('./routes/service_listings');

const tagsRoutes = require('./routes/tags');

const portfoliosRoutes = require('./routes/portfolios');

const jobsRoutes = require('./routes/jobs');

const job_attachmentsRoutes = require('./routes/job_attachments');

const proposalsRoutes = require('./routes/proposals');

const contractsRoutes = require('./routes/contracts');

const milestonesRoutes = require('./routes/milestones');

const deliverablesRoutes = require('./routes/deliverables');

const conversationsRoutes = require('./routes/conversations');

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

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

const paymentsRoutes = require('./routes/payments');

const invoicesRoutes = require('./routes/invoices');

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

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

const learning_articlesRoutes = require('./routes/learning_articles');

const ai_toolsRoutes = require('./routes/ai_tools');

const ai_tool_runsRoutes = require('./routes/ai_tool_runs');

const admin_announcementsRoutes = require('./routes/admin_announcements');


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: "FreelanceFusion MVP",
        description: "FreelanceFusion MVP 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/skills', passport.authenticate('jwt', {session: false}), skillsRoutes);

app.use('/api/service_categories', service_categoriesRoutes);

app.use('/api/service_listings', service_listingsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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);

  
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;
