import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import rateLimit from 'express-rate-limit';
import routes from './routes';

dotenv.config();

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

// P0-6: Rate Limiting
const limiter = rateLimit({
  windowMs: 24 * 60 * 60 * 1000, // 24 hours
  max: 5000, // limit each IP to 5000 requests per windowMs (increased for dev/testing)
  message: { error: 'Günlük kullanım limitine ulaştınız. (Too many requests)' }
});

app.use(cors());
// Varsayılan limit (100kb) OCR için gönderilen base64 taranmış sayfa görsellerini
// (300KB-1MB+ ham, base64 ile ~%33 daha büyük) kolayca aşıyordu ve 413 Payload
// Too Large ile reddediliyordu — bkz. /documents/ocr-image.
app.use(express.json({ limit: '25mb' }));

// If your app is behind a proxy (like Nginx, Docker ingress, etc.),
// the IP will default to the proxy's IP. We set trust proxy to get the real client IP.
app.set('trust proxy', 1); 

app.use(limiter); // Apply rate limiting to all requests

// Mount all API routes
app.use('/api', routes);

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});
