import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import morgan from 'morgan';
import { logger, stream } from './config/logger';
import { requestLogger } from './middleware/logging/requestLogger';
import { errorLogger } from './middleware/error/errorLogger';
import authRoutes from './routes/auth/index';
import userRoutes from './routes/users/index';
import articleRoutes from './routes/articles/index';
import galleryRoutes from './routes/gallery/index';
import imagesRoutes from './routes/images/index';
import authorRoutes from './routes/authors/index';
import otherRoutes from './routes/other/index';


const app = express();

// Загрузка переменных окружения
dotenv.config();

const PORT = process.env.PORT || 5000;

// Используем Morgan с кастомным логированием через Winston
app.use(morgan('combined', { stream }));

// Middleware для обработки JSON
app.use(cors());
app.use(express.json());
app.use(requestLogger);

// Обработка ошибок
app.use(errorLogger);

// Маршруты
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/authors', authorRoutes);
app.use('/api/articles', articleRoutes);
app.use('/api/gallery', galleryRoutes);
app.use('/api/images', imagesRoutes);
app.use('/api/other', otherRoutes);

// Запуск сервера
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
  logger.info(`Server running on port ${PORT}`);
});

// Обработка не перехваченных исключений
process.on('uncaughtException', (error) => {
  logger.error('Uncaught Exception:', error);
  process.exit(1);
});

// Обработка не обработанных promise rejections
process.on('unhandledRejection', (reason, promise) => {
  logger.error('Unhandled Rejection at:', promise, 'reason:', reason);
  process.exit(1);
});
