import { serve } from '@hono/node-server';
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger as honoLogger } from 'hono/logger';
import { compress } from 'hono/compress';
import { secureHeaders } from 'hono/secure-headers';
import { config, appConfig } from './config';
import { logger } from './utils/logger';

// Import routes
import { authRoutes } from './routes/auth';
import { websiteRoutes } from './routes/websites';
import { scanRoutes } from './routes/scans';
import { reportRoutes } from './routes/reports';
import { healthRoutes } from './routes/health';

// Import middleware
import { errorHandler } from './middleware/error-handler';
import { rateLimiter } from './middleware/rate-limiter';

const app = new Hono();

// Global middleware
app.use('*', honoLogger());
app.use('*', cors({
  origin: config.CORS_ORIGIN || '*',
  credentials: true,
}));
app.use('*', compress());
app.use('*', secureHeaders());

// Rate limiting
app.use('/api/*', rateLimiter());

// Health check (no auth required)
app.route('/health', healthRoutes);

// API routes
app.route('/api/auth', authRoutes);
app.route('/api/websites', websiteRoutes);
app.route('/api/scans', scanRoutes);
app.route('/api/reports', reportRoutes);

// 404 handler
app.notFound((c) => {
  return c.json({ error: 'Not Found' }, 404);
});

// Global error handler
app.onError(errorHandler);

// Start server
const port = config.PORT || 3001;

logger.info(`🚀 WCAG-ADA API Server starting on port ${port}...`);

serve({
  fetch: app.fetch,
  port,
}, (info) => {
  logger.info(`✅ Server is running on http://localhost:${info.port}`);
});

export default app;