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

const branchesRoutes = require('./routes/branches');

const fiscal_yearsRoutes = require('./routes/fiscal_years');

const user_role_assignmentsRoutes = require('./routes/user_role_assignments');

const app_menusRoutes = require('./routes/app_menus');

const role_permissionsRoutes = require('./routes/role_permissions');

const app_settingsRoutes = require('./routes/app_settings');

const currenciesRoutes = require('./routes/currencies');

const currency_ratesRoutes = require('./routes/currency_rates');

const numbering_profilesRoutes = require('./routes/numbering_profiles');

const widgetsRoutes = require('./routes/widgets');

const license_customersRoutes = require('./routes/license_customers');

const license_productsRoutes = require('./routes/license_products');

const license_keysRoutes = require('./routes/license_keys');

const license_activationsRoutes = require('./routes/license_activations');

const counterpartiesRoutes = require('./routes/counterparties');

const cost_centersRoutes = require('./routes/cost_centers');

const projectsRoutes = require('./routes/projects');

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

const cash_boxesRoutes = require('./routes/cash_boxes');

const banksRoutes = require('./routes/banks');

const bank_accountsRoutes = require('./routes/bank_accounts');

const letters_of_creditRoutes = require('./routes/letters_of_credit');

const pos_terminalsRoutes = require('./routes/pos_terminals');

const sales_item_groupsRoutes = require('./routes/sales_item_groups');

const warehouse_item_groupsRoutes = require('./routes/warehouse_item_groups');

const customer_groupsRoutes = require('./routes/customer_groups');

const analytic_dimensionsRoutes = require('./routes/analytic_dimensions');

const accountsRoutes = require('./routes/accounts');

const journal_voucher_typesRoutes = require('./routes/journal_voucher_types');

const journal_vouchersRoutes = require('./routes/journal_vouchers');

const journal_linesRoutes = require('./routes/journal_lines');

const approval_workflowsRoutes = require('./routes/approval_workflows');

const workflow_stepsRoutes = require('./routes/workflow_steps');

const voucher_approvalsRoutes = require('./routes/voucher_approvals');

const year_end_operationsRoutes = require('./routes/year_end_operations');

const report_definitionsRoutes = require('./routes/report_definitions');

const report_runsRoutes = require('./routes/report_runs');

const chat_conversationsRoutes = require('./routes/chat_conversations');

const chat_participantsRoutes = require('./routes/chat_participants');

const chat_messagesRoutes = require('./routes/chat_messages');

const form_alarmsRoutes = require('./routes/form_alarms');

const data_export_jobsRoutes = require('./routes/data_export_jobs');


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: "Secure Accounting Suite",
        description: "Secure Accounting Suite 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/businesses', passport.authenticate('jwt', {session: false}), businessesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
