require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const app = express();

// ✅ 요청 바디 용량 제한 확장
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
app.use(express.json({ limit: '50mb' }));

// ✅ CORS 설정: 허용 origin 명시
app.use(cors({
  origin: function (origin, callback) {
    const allowedOrigins = [
      'https://ahn.hyungi.net',
      'https://tech.hyungi.net',
      'https://pdf.hyungi.net'
    ];
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('CORS 차단됨: ' + origin));
    }
  }
}));

// ✅ 라우터 등록
const authRoutes = require('./routes/authRoutes');
const projectRoutes = require('./routes/projectRoutes');
const workerRoutes = require('./routes/workerRoutes');
const taskRoutes = require('./routes/taskRoutes');
const processRoutes = require('./routes/processRoutes');
const workReportRoutes = require('./routes/workReportRoutes');
const cuttingPlanRoutes = require('./routes/cuttingPlanRoutes');
const factoryInfoRoutes = require('./routes/factoryInfoRoutes');
const equipmentListRoutes = require('./routes/equipmentListRoutes');
const toolsRoute = require('./routes/toolsRoute');
const uploadRoutes = require('./routes/uploadRoutes');
const uploadBgRoutes = require('./routes/uploadBgRoutes');
const dailyIssueReportRoutes = require('./routes/dailyIssueReportRoutes');
const issueTypeRoutes = require('./routes/issueTypeRoutes');
const healthRoutes = require('./routes/healthRoutes');
const pipeSpecRoutes = require('./routes/pipeSpecRoutes');

// ahn.hyungi.net 배포용
app.use(express.static(path.join(__dirname, 'public')));

// ✅ 업로드된 파일 정적 라우팅 추가 (웹에서 이미지 접근 가능하게)
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// ✅ 각 라우트 등록
app.use('/api/auth', authRoutes);
app.use('/api/projects', projectRoutes);
app.use('/api/workers', workerRoutes);
app.use('/api/tasks', taskRoutes);
app.use('/api/processes', processRoutes);
app.use('/api/workreports', workReportRoutes);
app.use('/api/cuttingplans', cuttingPlanRoutes);
app.use('/api/factoryinfo', factoryInfoRoutes);
app.use('/api/equipment', equipmentListRoutes);
app.use('/api/tools', toolsRoute);
app.use('/api/uploads', uploadRoutes);
app.use('/api', uploadBgRoutes); // ✅ upload-bg 경로용
app.use('/api/issue-reports', dailyIssueReportRoutes);
app.use('/api/issue-types', issueTypeRoutes);
app.use('/api', healthRoutes);
app.use('/api/pipespecs', pipeSpecRoutes);

// ✅ 서버 실행
const PORT = process.env.PORT || 3005;
app.listen(PORT, () => {
  console.log(`🚀 서버가 ${PORT}번 포트에서 실행 중...`);
}).on('error', (err) => {
  console.error('❌ 서버 실행 중 오류 발생:', err);
});

app.use((req, res) => {
  res.status(404).json({ error: '존재하지 않는 경로입니다.' });
});