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

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

const user_rolesRoutes = require('./routes/user_roles');

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

const product_categoriesRoutes = require('./routes/product_categories');

const productsRoutes = require('./routes/products');

const price_listsRoutes = require('./routes/price_lists');

const price_list_itemsRoutes = require('./routes/price_list_items');

const warehousesRoutes = require('./routes/warehouses');

const inventory_batchesRoutes = require('./routes/inventory_batches');

const inventory_transactionsRoutes = require('./routes/inventory_transactions');

const stock_adjustmentsRoutes = require('./routes/stock_adjustments');

const stock_adjustment_linesRoutes = require('./routes/stock_adjustment_lines');

const interbranch_transfersRoutes = require('./routes/interbranch_transfers');

const transfer_linesRoutes = require('./routes/transfer_lines');

const suppliersRoutes = require('./routes/suppliers');

const supplier_productsRoutes = require('./routes/supplier_products');

const purchase_ordersRoutes = require('./routes/purchase_orders');

const purchase_order_linesRoutes = require('./routes/purchase_order_lines');

const goods_receiptsRoutes = require('./routes/goods_receipts');

const goods_receipt_linesRoutes = require('./routes/goods_receipt_lines');

const supplier_invoicesRoutes = require('./routes/supplier_invoices');

const customersRoutes = require('./routes/customers');

const loyalty_programsRoutes = require('./routes/loyalty_programs');

const pos_registersRoutes = require('./routes/pos_registers');

const pos_shiftsRoutes = require('./routes/pos_shifts');

const salesRoutes = require('./routes/sales');

const sale_linesRoutes = require('./routes/sale_lines');

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

const refundsRoutes = require('./routes/refunds');

const store_checklistsRoutes = require('./routes/store_checklists');

const checklist_itemsRoutes = require('./routes/checklist_items');

const checklist_runsRoutes = require('./routes/checklist_runs');

const checklist_run_itemsRoutes = require('./routes/checklist_run_items');

const risk_alertsRoutes = require('./routes/risk_alerts');

const departmentsRoutes = require('./routes/departments');

const employeesRoutes = require('./routes/employees');

const work_shiftsRoutes = require('./routes/work_shifts');

const shift_assignmentsRoutes = require('./routes/shift_assignments');

const attendance_recordsRoutes = require('./routes/attendance_records');

const payroll_runsRoutes = require('./routes/payroll_runs');

const payroll_itemsRoutes = require('./routes/payroll_items');

const performance_reviewsRoutes = require('./routes/performance_reviews');

const chart_accountsRoutes = require('./routes/chart_accounts');

const journal_entriesRoutes = require('./routes/journal_entries');

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

const expensesRoutes = require('./routes/expenses');

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

const marketing_campaignsRoutes = require('./routes/marketing_campaigns');

const campaign_recipientsRoutes = require('./routes/campaign_recipients');

const ai_reorder_suggestionsRoutes = require('./routes/ai_reorder_suggestions');


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: "Retail Ops Management System",
        description: "Retail Ops Management System 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/companies', passport.authenticate('jwt', {session: false}), companiesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
