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



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

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

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

const organizationsRoutes = require('./routes/organizations');

const firmsRoutes = require('./routes/firms');

const merchantsRoutes = require('./routes/merchants');

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

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

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

const receiptsRoutes = require('./routes/receipts');

const ocr_extractionsRoutes = require('./routes/ocr_extractions');

const sales_invoicesRoutes = require('./routes/sales_invoices');

const sales_invoice_linesRoutes = require('./routes/sales_invoice_lines');

const purchase_invoicesRoutes = require('./routes/purchase_invoices');

const purchase_invoice_linesRoutes = require('./routes/purchase_invoice_lines');

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

const tax_periodsRoutes = require('./routes/tax_periods');

const vat_declarationsRoutes = require('./routes/vat_declarations');

const tot_declarationsRoutes = require('./routes/tot_declarations');

const declaration_submissionsRoutes = require('./routes/declaration_submissions');

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

const audit_eventsRoutes = require('./routes/audit_events');
const transactionsRoutes = require('./routes/transactions');
const dashboardRoutes = require('./routes/dashboard');
const contextRoutes = require('./routes/context');


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: "SmartHisab",
        description: "SmartHisab 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/firms', passport.authenticate('jwt', {session: false}), firmsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/audit_events', passport.authenticate('jwt', {session: false}), audit_eventsRoutes);
app.use('/api/transactions', passport.authenticate('jwt', {session: false}), transactionsRoutes);
app.use('/api/dashboard', passport.authenticate('jwt', {session: false}), dashboardRoutes);
app.use('/api/context', contextRoutes);

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

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

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;