import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import pool from './config/db';
import {
    authLimiter,
    authSlowDown,
    globalLimiter,
    requestTimeout,
    securityHeaders
} from './middlewares/security';

import messagesRouter from './routes/messages';
import authCodeRouter from './routes/authCode';
import supportRouter from './routes/support';
import cookieConsentRouter from './routes/cookieConsent';

dotenv.config();

const app = express();
const port = process.env.PORT || 3000;
const allowedOrigins = String(process.env.CORS_ORIGINS || '')
    .split(',')
    .map((origin) => origin.trim())
    .filter(Boolean);

app.set('trust proxy', 1);
app.use(securityHeaders);
app.use(globalLimiter);
app.use(
    cors({
        origin: allowedOrigins.length > 0 ? allowedOrigins : true,
        methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
        credentials: false
    })
);
app.use(express.json({ limit: '20kb' }));
app.use(express.urlencoded({ extended: false, limit: '20kb' }));
app.use(requestTimeout(15_000));

app.use('/api/messages', messagesRouter);
app.use('/api/support', supportRouter);
app.use('/api/auth', requestTimeout(8_000), authSlowDown, authLimiter, authCodeRouter);
app.use('/api/cookies', requestTimeout(8_000), cookieConsentRouter);

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

// Database connection test
app.get('/api/test-db', async (req, res) => {
    try {
        const [rows] = await pool.query('SELECT 1 + 1 AS solution');
        res.json({ status: 'connected', result: rows });
    } catch (error: any) {
        console.error('Database connection error:', error);
        res.status(500).json({ status: 'error', message: error.message });
    }
});

app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});
