import 'dotenv/config';
import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';

// ── Simple Rate Limiter (in-memory) ──────────────────────────────────────────
const rateLimitStore = new Map<string, { count: number; resetAt: number }>();
function rateLimit(maxReqs: number, windowMs: number) {
  return (req: Request, res: Response, next: NextFunction) => {
    const key = req.ip || 'unknown';
    const now = Date.now();
    const entry = rateLimitStore.get(key);
    if (!entry || now > entry.resetAt) {
      rateLimitStore.set(key, { count: 1, resetAt: now + windowMs });
      return next();
    }
    if (entry.count >= maxReqs) {
      res.setHeader('Retry-After', String(Math.ceil((entry.resetAt - now) / 1000)));
      return res.status(429).json({ error: 'Too many requests' });
    }
    entry.count++;
    next();
  };
}
// Cleanup stale entries every 5min
setInterval(() => {
  const now = Date.now();
  for (const [key, val] of rateLimitStore) {
    if (now > val.resetAt) rateLimitStore.delete(key);
  }
}, 300_000);

import authRoutes from './routes/auth';
import burrowRoutes from './routes/burrows';
import sightingRoutes from './routes/sightings';
import eventRoutes from './routes/events';
import streamRoutes from './routes/streams';
import donationRoutes from './routes/donations';
import volunteerRoutes from './routes/volunteer';
import statsRoutes from './routes/stats';

import { errorHandler, notFound } from './middleware/errorHandler';

const app = express();
const PORT = parseInt(process.env.PORT || '3020', 10);
const HOST = process.env.HOST || '0.0.0.0';

// ── Core Middleware ────────────────────────────────────────────────────────────
app.use(express.json({ limit: '2mb' }));
app.use(express.urlencoded({ extended: true }));

app.use(cors({
  origin: process.env.ALLOWED_ORIGINS?.split(',') || ['http://localhost:3000'],
  credentials: true,
}));

// ── Security Headers ──────────────────────────────────────────────────────────
app.use((_req, res, next) => {
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.setHeader('X-Frame-Options', 'DENY');
  res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
  next();
});

// ── Health Check ──────────────────────────────────────────────────────────────
app.get('/api/health', (_req, res) => {
  res.json({ status: 'ok', service: 'owl-stream-backend', timestamp: new Date().toISOString() });
});

// ── Rate Limiting ─────────────────────────────────────────────────────────────
app.use('/api/auth', rateLimit(10, 15 * 60 * 1000)); // 10 req / 15 min on auth
app.use('/api', rateLimit(120, 60 * 1000));           // 120 req / min general

// ── Routes ────────────────────────────────────────────────────────────────────
app.use('/api/auth',      authRoutes);
app.use('/api/burrows',   burrowRoutes);
app.use('/api/sightings', sightingRoutes);
app.use('/api/events',    eventRoutes);
app.use('/api/streams',   streamRoutes);
app.use('/api/donations', donationRoutes);
app.use('/api/volunteer', volunteerRoutes);
app.use('/api/stats',     statsRoutes);

// ── Error Handling ────────────────────────────────────────────────────────────
app.use(notFound);
app.use(errorHandler);

app.listen(PORT, HOST, () => {
  console.log(`🦉 Owl Stream Backend listening on http://${HOST}:${PORT}`);
});

export default app;
