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

const locationsRoutes = require('./routes/locations');

const player_profilesRoutes = require('./routes/player_profiles');

const customization_itemsRoutes = require('./routes/customization_items');

const toolsRoutes = require('./routes/tools');

const item_categoriesRoutes = require('./routes/item_categories');

const itemsRoutes = require('./routes/items');

const npcsRoutes = require('./routes/npcs');

const familiesRoutes = require('./routes/families');

const family_membershipsRoutes = require('./routes/family_memberships');

const npc_relationshipsRoutes = require('./routes/npc_relationships');

const dialogue_topicsRoutes = require('./routes/dialogue_topics');

const dialogue_linesRoutes = require('./routes/dialogue_lines');

const questsRoutes = require('./routes/quests');

const quest_objectivesRoutes = require('./routes/quest_objectives');

const market_storesRoutes = require('./routes/market_stores');

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

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

const store_productsRoutes = require('./routes/store_products');

const store_inventory_batchesRoutes = require('./routes/store_inventory_batches');

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

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

const deliveriesRoutes = require('./routes/deliveries');

const shelvesRoutes = require('./routes/shelves');

const shelf_slotsRoutes = require('./routes/shelf_slots');

const cash_registersRoutes = require('./routes/cash_registers');

const sales_transactionsRoutes = require('./routes/sales_transactions');

const sales_transaction_linesRoutes = require('./routes/sales_transaction_lines');

const daily_reportsRoutes = require('./routes/daily_reports');

const weather_statesRoutes = require('./routes/weather_states');

const world_calendar_daysRoutes = require('./routes/world_calendar_days');

const price_modifiersRoutes = require('./routes/price_modifiers');

const cropsRoutes = require('./routes/crops');

const farm_plotsRoutes = require('./routes/farm_plots');

const plantingsRoutes = require('./routes/plantings');

const fish_speciesRoutes = require('./routes/fish_species');

const fishing_spotsRoutes = require('./routes/fishing_spots');

const fishing_catchesRoutes = require('./routes/fishing_catches');

const crafting_recipesRoutes = require('./routes/crafting_recipes');

const recipe_ingredientsRoutes = require('./routes/recipe_ingredients');

const buildingsRoutes = require('./routes/buildings');

const construction_projectsRoutes = require('./routes/construction_projects');

const festivalsRoutes = require('./routes/festivals');

const festival_attendanceRoutes = require('./routes/festival_attendance');

const random_eventsRoutes = require('./routes/random_events');


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: "Ilha Market",
        description: "Ilha Market 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/world_regions', passport.authenticate('jwt', {session: false}), world_regionsRoutes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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;

  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`);
  });

module.exports = app;
