const express = require('express');
const router = express.Router();
const { Pool } = require('pg');
const { verifyToken } = require('../middleware/auth');

const pgPool = new Pool({
    host: process.env.PGHOST || 'postgres',
    port: process.env.PGPORT || 5432,
    user: process.env.PGUSER || 'postgres',
    password: process.env.PGPASSWORD || 'postgres',
    database: process.env.PGDATABASE || 'ckqr',
});

// Get all folders for user
router.get('/', verifyToken, async (req, res) => {
    try {
        const result = await pgPool.query(
            'SELECT * FROM folders WHERE user_id = $1 ORDER BY created_at DESC',
            [req.user.id]
        );
        res.json({ folders: result.rows });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Server error fetching folders' });
    }
});

// Create a new folder
router.post('/', verifyToken, async (req, res) => {
    const { name } = req.body;
    if (!name) return res.status(400).json({ error: 'Folder name is required' });

    try {
        const result = await pgPool.query(
            'INSERT INTO folders (user_id, name) VALUES ($1, $2) RETURNING *',
            [req.user.id, name]
        );
        res.json({ message: 'Folder created', folder: result.rows[0] });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Server error creating folder' });
    }
});

// Delete a folder
router.delete('/:id', verifyToken, async (req, res) => {
    try {
        const result = await pgPool.query(
            'DELETE FROM folders WHERE id = $1 AND user_id = $2 RETURNING id',
            [req.params.id, req.user.id]
        );
        if (result.rows.length === 0) return res.status(404).json({ error: 'Folder not found or unauthorized' });
        res.json({ message: 'Folder deleted' });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Error deleting folder' });
    }
});

module.exports = router;
