require('dotenv').config();
const express = require('express');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const gscRouter     = require('./routes/gsc');
const clickupRouter = require('./routes/clickup');
const ahrefsRouter  = require('./routes/ahrefs');
const sheetsRouter  = require('./routes/sheets');
const insightsRouter= require('./routes/insights');

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

app.use(cors({ origin: 'http://localhost:5173' }));
app.use(express.json());

const limiter = rateLimit({ windowMs: 60 * 1000, max: 60 });
app.use('/api/', limiter);

app.use('/api/gsc',      gscRouter);
app.use('/api/clickup',  clickupRouter);
app.use('/api/ahrefs',   ahrefsRouter);
app.use('/api/sheets',   sheetsRouter);
app.use('/api/insights', insightsRouter);

app.get('/api/health', (req, res) => res.json({ status: 'ok', ts: new Date().toISOString() }));

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: err.message || 'Internal server error' });
});

app.listen(PORT, () => console.log(`SEO Dashboard API running on http://localhost:${PORT}`));
