import { Router } from 'express';
import multer from 'multer';
import path from 'path';
import { v4 as uuidv4 } from 'uuid';
import * as dataSheetController from '../controllers/dataSheetController.js';
import { extractUser, requireAdmin } from '../middleware/authMiddleware.js';
import os from 'os';

const router = Router();

// Configure Multer
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, os.tmpdir());
    },
    filename: (req, file, cb) => {
        const uniqueSuffix = `${Date.now()}-${uuidv4()}`;
        cb(null, `${uniqueSuffix}${path.extname(file.originalname)}`);
    }
});

const upload = multer({
    storage,
    limits: { fileSize: 10 * 1024 * 1024 }, // 10MB limit
    fileFilter: (req, file, cb) => {
        if (file.mimetype === 'application/pdf' || file.mimetype.startsWith('image/')) {
            cb(null, true);
        } else {
            cb(new Error('Only PDF and image files are allowed'));
        }
    }
});

// Public routes (read-only)
router.get('/', dataSheetController.getAllDataSheets);
router.get('/file/:id', dataSheetController.getFile);

// Protected routes (require edit permission)
router.post('/', extractUser, requireAdmin, upload.single('file'), dataSheetController.createDataSheet);
router.post('/extract', extractUser, requireAdmin, upload.single('file'), dataSheetController.extractData);
router.put('/:id', extractUser, requireAdmin, upload.single('file'), dataSheetController.updateDataSheet);
router.delete('/:id', extractUser, requireAdmin, dataSheetController.deleteDataSheet);

export default router;
