const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const http = require('http');
require('dotenv').config();

// Erhöhe maxHttpHeaderSize für Node.js (Standard ist 8KB, erhöhe auf 16KB)
if (http.maxHeaderSize !== undefined) {
  http.maxHeaderSize = 16384;
}
const sequelize = require('./config/database');
const authRouter = require('./routes/auth');
const eventTypesRouter = require('./routes/eventtypes');
const eventPlacesRouter = require('./routes/eventPlaces');
const contactPersonsRouter = require('./routes/contactPerson');
const positionsRouter = require('./routes/positions');
const institutionRouter = require('./routes/institutions');
const eventRouter = require('./routes/event');
const menuDataRouter = require('./routes/menuData');
const worshipRouter = require('./routes/worships');
const worshipLeadersRouter = require('./routes/worshipLeaders');
const pageRouter = require('./routes/pages');
const userRouter = require('./routes/users');
const imageRouter = require('./routes/image');
const filesRouter = require('./routes/files');
const liturgicalDaysRouter = require('./routes/liturgicalDays');

const app = express();
const PORT = parseInt(process.env.BACKEND_PORT || process.env.PORT, 10) || 3000;

// CORS mit Whitelist und tolerantem Fallback für fehlende Origin-Header
const allowedOrigins = (process.env.ALLOWED_ORIGINS || '')
  .split(',')
  .map(s => s.trim())
  .filter(Boolean);

app.use(cors({
  origin: (origin, callback) => {
    if (!origin) {
      return callback(null, true); // z.B. Healthchecks/curl/Server-zu-Server
    }
    
    if (allowedOrigins.length === 0) {
      return callback(null, true); // Fallback: alles erlauben
    }
    
    // Prüfe exakte Übereinstimmung
    if (allowedOrigins.includes(origin)) {
      return callback(null, true);
    }
    
    // Für Entwicklung: Erlaube localhost und torstens auf jedem Port
    try {
      const originUrl = new URL(origin);
      const hostname = originUrl.hostname.toLowerCase();
      const isLocalhost = hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1';
      const isTorstens = hostname === 'torstens' || hostname.includes('torstens');
      
      if (isLocalhost || isTorstens) {
        return callback(null, true);
      }
    } catch (e) {
      // Falls URL-Parsing fehlschlägt, prüfe mit Regex
      const isLocalhost = /^https?:\/\/(localhost|127\.0\.0\.1|::1)(:\d+)?$/.test(origin);
      const isTorstens = /^https?:\/\/torstens(:\d+)?/.test(origin);
      
      if (isLocalhost || isTorstens) {
        return callback(null, true);
      }
    }
    
    // Prüfe auch ohne Port (für Flexibilität)
    const originWithoutPort = origin.replace(/:\d+$/, '');
    const allowedWithoutPort = allowedOrigins.some(allowed => {
      const allowedWithoutPort = allowed.replace(/:\d+$/, '');
      return originWithoutPort === allowedWithoutPort;
    });
    
    if (allowedWithoutPort) {
      return callback(null, true);
    }
    
    return callback(new Error('Not allowed by CORS'), false);
  },
  credentials: true,
  methods: ['GET','POST','PUT','PATCH','DELETE','OPTIONS'],
  allowedHeaders: ['Content-Type','Authorization']
}));
// Express 5 nutzt path-to-regexp v6; '*' ist dort als Pattern ungueltig.
app.options('/{*any}', cors());

// Erhöhe Header-Limits für große Requests
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));

// Erhöhe maxHttpHeaderSize (Node.js 18.3.0+)
if (process.versions.node.split('.')[0] >= 18) {
  require('http').maxHeaderSize = 16384; // 16KB (Standard ist 8KB)
}

app.use('/api/auth', authRouter);
app.use('/api/event-types', eventTypesRouter);
app.use('/api/event-places', eventPlacesRouter);
app.use('/api/contact-persons', contactPersonsRouter);
app.use('/api/positions', positionsRouter);
app.use('/api/institutions', institutionRouter);
app.use('/api/events', eventRouter);
app.use('/api/menu-data', menuDataRouter);
app.use('/api/worships', worshipRouter);
app.use('/api/worship-leaders', worshipLeadersRouter);
app.use('/api/page-content', pageRouter);
app.use('/api/users', userRouter);
app.use('/api/image', imageRouter);
app.use('/api/files', filesRouter);
app.use('/api/liturgical-days', liturgicalDaysRouter);

sequelize.sync().then(() => {
  app.listen(PORT, '0.0.0.0', () => {
    console.log(`Server läuft auf Port ${PORT} (IPv4 und IPv6)`);
  });
});
