import express from 'express';
import cors from 'cors';
import scrapeRoutes from './routes/scrape';
import filtersRoutes from './routes/filters';
import exportsRoutes from './routes/exports';
import { getDb, closeDb } from './db/schema';

const PORT = parseInt(process.env.PORT || '3847');
const API_KEY = process.env.REONOMY_API_KEY || 'reonomy-dev-key';

const app = express();

// Middleware
app.use(cors());
app.use(express.json());

// API Key auth middleware
app.use('/api', (req, res, next) => {
  // Skip auth for health check
  if (req.path === '/health') return next();

  const key = req.headers['x-api-key'] as string;
  if (!key || key !== API_KEY) {
    return res.status(401).json({ error: 'Invalid or missing API key. Set X-API-Key header.' });
  }
  next();
});

// Routes
app.use('/api/scrape', scrapeRoutes);
app.use('/api/filters', filtersRoutes);
app.use('/api/exports', exportsRoutes);

// Health check (no auth)
app.get('/api/health', (_req, res) => {
  res.json({
    status: 'ok',
    service: 'reonomy-api',
    version: '1.0.0',
    timestamp: new Date().toISOString(),
  });
});

// Initialize DB on startup
getDb();

// Start server
app.listen(PORT, () => {
  console.log(`🏢 Reonomy API Server running on http://localhost:${PORT}`);
  console.log(`   Health: http://localhost:${PORT}/api/health`);
  console.log(`   API Key: ${API_KEY.substring(0, 8)}...`);
});

// Graceful shutdown
process.on('SIGINT', () => {
  console.log('\nShutting down...');
  closeDb();
  process.exit(0);
});

process.on('SIGTERM', () => {
  closeDb();
  process.exit(0);
});

export default app;
