import cors from 'cors';
import dotenv from 'dotenv';
import express from 'express';
import session from 'express-session';
import path from 'path';
import { fileURLToPath } from 'url';
import { restartLdapSyncScheduler } from './integrations.js';
import { createApiRouter } from './routes/api/index.js';
import { createAdminRouter } from './routes/admin/index.js';
import authRouter from './routes/auth.js';

dotenv.config();

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const app = express();
const PORT = process.env.PORT || 3000;

app.set('trust proxy', 1);
app.use(
  cors({
    origin: true,
    credentials: true,
  }),
);
app.use(express.json());
app.use(
  session({
    name: 'crm.sid',
    secret: process.env.SESSION_SECRET || 'crm-dev-secret-change-in-production',
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      sameSite: 'lax',
      maxAge: 7 * 24 * 60 * 60 * 1000,
    },
  }),
);

app.use('/auth', authRouter);
app.use('/api', createApiRouter());
app.use('/api', createAdminRouter());

/** Unbekannte /api/*-Routen: JSON 404 */
app.use('/api', (req, res) => {
  res.status(404).json({ message: 'API nicht gefunden' });
});

app.get('/', (_req, res) => {
  res.redirect(302, '/start.html');
});

app.use(express.static(path.join(__dirname, '..', 'public')));

app.listen(PORT, () => {
  restartLdapSyncScheduler();
  console.log(`CRM-Server http://localhost:${PORT}`);
});
