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

const workspace_membershipsRoutes = require('./routes/workspace_memberships');

const service_catalog_itemsRoutes = require('./routes/service_catalog_items');

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

const propertiesRoutes = require('./routes/properties');

const job_templatesRoutes = require('./routes/job_templates');

const jobsRoutes = require('./routes/jobs');

const job_assignmentsRoutes = require('./routes/job_assignments');

const checklistsRoutes = require('./routes/checklists');

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

const job_checklist_runsRoutes = require('./routes/job_checklist_runs');

const job_checklist_run_itemsRoutes = require('./routes/job_checklist_run_items');

const job_mediaRoutes = require('./routes/job_media');

const invoicesRoutes = require('./routes/invoices');

const invoice_line_itemsRoutes = require('./routes/invoice_line_items');

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

const estimatesRoutes = require('./routes/estimates');

const estimate_line_itemsRoutes = require('./routes/estimate_line_items');

const recurring_schedulesRoutes = require('./routes/recurring_schedules');

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

const support_ticketsRoutes = require('./routes/support_tickets');

const plansRoutes = require('./routes/plans');

const subscriptionsRoutes = require('./routes/subscriptions');


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: "CleanerOps SaaS",
        description: "CleanerOps SaaS 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/workspaces', passport.authenticate('jwt', {session: false}), workspacesRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;
