const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const riskController = require('../controllers/riskController');
const { requireAuth, requirePage } = require('../middleware/auth');

// 업로드 디렉토리 (multer destination에서 lazy 생성)
const uploadDir = path.join(__dirname, '..', 'uploads', 'risk');

// Multer 설정
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    try { if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true }); } catch (e) { /* ignore */ }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    cb(null, `${req.params.mitigationId}_photo_${Date.now()}${ext}`);
  }
});
const upload = multer({
  storage,
  limits: { fileSize: 10 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    const allowed = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
    const ext = path.extname(file.originalname).toLowerCase();
    cb(null, allowed.includes(ext));
  }
});

router.use(requireAuth);

// 공정 템플릿
router.get('/templates', riskController.getTemplates);

// 프로젝트 CRUD
router.get('/projects', riskController.getAllProjects);
router.post('/projects', riskController.createProject);
router.get('/projects/:id', riskController.getProjectById);
router.patch('/projects/:id', riskController.updateProject);
router.delete('/projects/:id', requirePage('safety_risk_assessment'), riskController.deleteProject);

// 세부 공정 추가 (수시 평가용)
router.post('/projects/:id/processes', riskController.addProcess);

// Excel 내보내기
router.get('/projects/:id/export', riskController.exportExcel);

// 평가 항목 CRUD
router.post('/processes/:processId/items', riskController.createItem);
router.patch('/items/:itemId', riskController.updateItem);
router.delete('/items/:itemId', requirePage('safety_risk_assessment'), riskController.deleteItem);

// 감소대책 CRUD
router.get('/projects/:id/mitigations', riskController.getMitigations);
router.post('/projects/:id/mitigations', riskController.createMitigation);
router.patch('/mitigations/:mitigationId', riskController.updateMitigation);
router.post('/mitigations/:mitigationId/photo', upload.single('photo'), riskController.uploadPhoto);

module.exports = router;
