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

const user_profile_typesRoutes = require('./routes/user_profile_types');

const declarationsRoutes = require('./routes/declarations');

const dependentsRoutes = require('./routes/dependents');

const data_sourcesRoutes = require('./routes/data_sources');

const transactionsRoutes = require('./routes/transactions');

const documentsRoutes = require('./routes/documents');

const income_payers_pjRoutes = require('./routes/income_payers_pj');

const income_carne_leao_monthlyRoutes = require('./routes/income_carne_leao_monthly');

const exempt_incomesRoutes = require('./routes/exempt_incomes');

const exclusive_incomesRoutes = require('./routes/exclusive_incomes');

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

const debtsRoutes = require('./routes/debts');

const deductible_paymentsRoutes = require('./routes/deductible_payments');

const investment_positionsRoutes = require('./routes/investment_positions');

const tradesRoutes = require('./routes/trades');

const monthly_capital_gainsRoutes = require('./routes/monthly_capital_gains');

const risk_analysesRoutes = require('./routes/risk_analyses');

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

const organization_membershipsRoutes = require('./routes/organization_memberships');

const accountant_client_accessesRoutes = require('./routes/accountant_client_accesses');

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

const consentsRoutes = require('./routes/consents');

const job_runsRoutes = require('./routes/job_runs');


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: "DeclaraFácil",
        description: "DeclaraFácil 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/user_profiles', passport.authenticate('jwt', {session: false}), user_profilesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
