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

const organizationForAuthRoutes = require('./routes/organizationLogin');

const openaiRoutes = require('./routes/openai');

const contactFormRoutes = require('./routes/contactForm');

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

const access_rolesRoutes = require('./routes/access_roles');

const ai_agentsRoutes = require('./routes/ai_agents');

const alertsRoutes = require('./routes/alerts');

const automation_jobsRoutes = require('./routes/automation_jobs');

const campaignsRoutes = require('./routes/campaigns');

const compliance_auditsRoutes = require('./routes/compliance_audits');

const compliance_issuesRoutes = require('./routes/compliance_issues');

const expansion_plansRoutes = require('./routes/expansion_plans');

const infrastructure_statusesRoutes = require('./routes/infrastructure_statuses');

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

const market_signalsRoutes = require('./routes/market_signals');

const onboarding_casesRoutes = require('./routes/onboarding_cases');

const patient_messagesRoutes = require('./routes/patient_messages');

const patient_profilesRoutes = require('./routes/patient_profiles');

const platform_metricsRoutes = require('./routes/platform_metrics');

const pricing_strategiesRoutes = require('./routes/pricing_strategies');

const revenue_summariesRoutes = require('./routes/revenue_summaries');

const subscriber_activitiesRoutes = require('./routes/subscriber_activities');

const subscriber_rolesRoutes = require('./routes/subscriber_roles');

const subscribersRoutes = require('./routes/subscribers');

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

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

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

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

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: 'Patient Vault',
      description:
        'Patient Vault 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/access_roles',
  passport.authenticate('jwt', { session: false }),
  access_rolesRoutes,
);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

app.use('/api/contact-form', contactFormRoutes);

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

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;
