import { Router } from 'express';
import * as inspectionController from '../controllers/inspectionController.js';
import multer from 'multer';
import path from 'path';
import { v4 as uuidv4 } from 'uuid';
import os from 'os';

const router = Router();

// Configure Multer for uploads
// In serverless environments (Netlify), we must use /tmp or memory
// We use /tmp but be aware files are ephemeral in serverless
const uploadsDir = path.join(os.tmpdir(), 'uploads');

// Ensure uploads directory exists (safe in /tmp)
import fs from 'fs';
if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
}

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

const upload = multer({
    storage,
    limits: { fileSize: 500 * 1024 }, // 500KB limit
    fileFilter: (req, file, cb) => {
        if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg') {
            cb(null, true);
        } else {
            cb(new Error('Only JPG/JPEG images are allowed'));
        }
    }
});

// Upload route
router.post('/upload', upload.single('photo'), inspectionController.uploadPhoto);

// Public routes (read-only)
router.get('/', inspectionController.getAllInspections);
router.get('/project/:projectId', inspectionController.getInspectionsByProject);

// Modification routes
router.post('/', inspectionController.createInspection);
router.put('/:id', inspectionController.updateInspection);
router.delete('/:id', inspectionController.deleteInspection);

export default router;
