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

const holidaysRoutes = require('./routes/holidays');

const sss_contribution_tablesRoutes = require('./routes/sss_contribution_tables');

const withholding_tax_tablesRoutes = require('./routes/withholding_tax_tables');

const fiscal_periodsRoutes = require('./routes/fiscal_periods');

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

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

const positionsRoutes = require('./routes/positions');

const shiftsRoutes = require('./routes/shifts');

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

const employee_documentsRoutes = require('./routes/employee_documents');

const time_recordsRoutes = require('./routes/time_records');

const biometric_importsRoutes = require('./routes/biometric_imports');

const leave_typesRoutes = require('./routes/leave_types');

const leave_balancesRoutes = require('./routes/leave_balances');

const leave_applicationsRoutes = require('./routes/leave_applications');

const employee_loansRoutes = require('./routes/employee_loans');

const loan_deductionsRoutes = require('./routes/loan_deductions');

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

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

const bank_filesRoutes = require('./routes/bank_files');

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

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

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

const vendorsRoutes = require('./routes/vendors');

const ap_invoicesRoutes = require('./routes/ap_invoices');

const ap_paymentsRoutes = require('./routes/ap_payments');

const ap_payment_linesRoutes = require('./routes/ap_payment_lines');

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

const ar_invoicesRoutes = require('./routes/ar_invoices');

const ar_invoice_itemsRoutes = require('./routes/ar_invoice_items');

const job_requisitionsRoutes = require('./routes/job_requisitions');

const applicantsRoutes = require('./routes/applicants');

const approval_requestsRoutes = require('./routes/approval_requests');

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

const export_requestsRoutes = require('./routes/export_requests');

const password_historiesRoutes = require('./routes/password_histories');

const refresh_tokensRoutes = require('./routes/refresh_tokens');

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


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: "Ogami ERP Phase 1",
        description: "Ogami ERP Phase 1 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/system_parameters', passport.authenticate('jwt', {session: false}), system_parametersRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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/bank_files', passport.authenticate('jwt', {session: false}), bank_filesRoutes);

app.use('/api/accounts', passport.authenticate('jwt', {session: false}), 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/vendors', passport.authenticate('jwt', {session: false}), vendorsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
