import { Router } from 'express';
import pool from '../db.js';
import { v4 as uuidv4 } from 'uuid';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
const router = Router();
// Configure storage
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        const uploadDir = 'uploads/';
        // Create directory if it doesn't exist
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir);
        }
        cb(null, uploadDir);
    },
    filename: (req, file, cb) => {
        // Unique filename: timestamp-random-originalName
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname));
    }
});
const upload = multer({ storage: storage });
// Get documents for a project
router.get('/:projectId', async (req, res) => {
    try {
        const [rows] = await pool.query('SELECT * FROM documents WHERE project_id = ? ORDER BY created_at DESC', [req.params.projectId]);
        res.json(rows);
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});
// Upload document
router.post('/', upload.single('file'), async (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: 'No file uploaded' });
        }
        const { project_id } = req.body;
        const id = uuidv4();
        // Construct public URL - assuming server serves 'uploads' at root or /uploads
        // We'll configure server.ts to serve 'uploads' folder at '/uploads'
        const url = `/uploads/${req.file.filename}`;
        await pool.query('INSERT INTO documents (id, project_id, name, type, url, size) VALUES (?, ?, ?, ?, ?, ?)', [id, project_id, req.file.originalname, req.file.mimetype, url, req.file.size]);
        res.status(201).json({
            id,
            project_id,
            name: req.file.originalname,
            type: req.file.mimetype,
            url,
            size: req.file.size
        });
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});
export default router;
//# sourceMappingURL=documents.js.map