import express from 'express';

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const multer = require('multer');

import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const router = express.Router();

const storage = multer.diskStorage({
    destination: path.join(__dirname, '../uploads'),
    filename: (req, file, cb) => {
        cb(null, Date.now() + '-' + file.originalname);
    }
});
const upload = multer({ storage });

router.get('/upload', (req, res) => {
    if (!req.user) return res.redirect('/');
    res.render('upload', { user: req.user });
});

router.post('/upload', upload.single('image'), (req, res) => {
    const { title, description } = req.body;
    const imagePath = `/uploads/${req.file.filename}`;
    // TODO: hier später in DB speichern
    console.log({ title, description, imagePath });
    res.send(`<p>Upload erfolgreich!</p><a href="/upload">Neues Bild hochladen</a>`);
});

export default router;
