/**
 * System 2 - 신고 시스템 API Server
 *
 * TK-FB-Project에서 추출한 workIssue(신고) 전용 서비스
 */

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const path = require('path');
const logger = require('./utils/logger');
const { AuthenticationError, ForbiddenError } = require('./utils/errors');

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

app.set('trust proxy', 1);

// CORS
const allowedOrigins = [
  'https://tkfb.technicalkorea.net',
  'https://tkreport.technicalkorea.net',
  'https://tkqc.technicalkorea.net',
  'https://tkuser.technicalkorea.net',
];
if (process.env.NODE_ENV === 'development') {
  allowedOrigins.push('http://localhost:30080', 'http://localhost:30180', 'http://localhost:30280');
}
app.use(cors({
  origin: function(origin, cb) {
    if (!origin || allowedOrigins.includes(origin) || /^http:\/\/192\.168\.\d+\.\d+(:\d+)?$/.test(origin)) return cb(null, true);
    cb(new Error('CORS blocked: ' + origin));
  },
  credentials: true
}));

// Body parser
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// Static files (uploads)
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// Rate limiter
const apiLimiter = rateLimit({
  windowMs: 1 * 60 * 1000,
  max: 500,
  message: 'API 요청 한도를 초과했습니다.',
  standardHeaders: true,
  legacyHeaders: false
});
app.use('/api/', apiLimiter);

// Health check
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', service: 'system2-report', timestamp: new Date().toISOString() });
});

// JWT Auth middleware (middlewares/auth.js 사용)
const { requireAuth } = require('./middlewares/auth');

// Routes
const workIssueRoutes = require('./routes/workIssueRoutes');

// 인증이 필요한 API
app.use('/api/work-issues', requireAuth, workIssueRoutes);

// 404 (에러 핸들러보다 먼저 등록)
app.use((req, res) => {
  res.status(404).json({ success: false, error: 'Not Found', path: req.originalUrl });
});

// Error handler
app.use((err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  logger.error('API Error:', { error: err.message, path: req.path });
  res.status(statusCode).json({
    success: false,
    error: '서버 오류가 발생했습니다'
  });
});

app.listen(PORT, () => {
  console.log(`System 2 (신고) API running on port ${PORT}`);
});

module.exports = app;
