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';

import pool from '../db.js';

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'), async (req, res) => {
    const { title, description } = req.body;
    const filename = req.file.filename;

    const uploader = req.user ? req.user.displayName : 'Anonym';

    await pool.query(
        'INSERT INTO images (filename, title, description, uploader) VALUES ($1, $2, $3, $4)',
        [filename, title, description, uploader]
    );

    res.redirect('/');
});

router.post('/delete/:id', async (req, res) => {
    const imageId = req.params.id;

    // Bild aus DB laden
    const result = await pool.query('SELECT * FROM images WHERE id = $1', [imageId]);
    const image = result.rows[0];

    // Zugriffskontrolle
    const isOwner = req.user && image && req.user.displayName === image.uploader;
    const isAdmin = req.user && req.user.emails && req.user.emails[0].value === process.env.ADMIN_EMAIL;

    if (!isOwner && !isAdmin) {
        return res.status(403).send('🚫 Du darfst dieses Bild nicht löschen.');
    }

    // Datei löschen
    const filePath = path.join(__dirname, '../uploads', image.filename);
    fs.unlink(filePath, err => {
        if (err) console.warn('⚠️ Datei konnte nicht gelöscht werden:', err.message);
    });

    // DB-Eintrag löschen
    await pool.query('DELETE FROM images WHERE id = $1', [imageId]);

    res.redirect('/');
});

export default router;
