const db = require('../config/db');

exports.getNotes = async (req, res) => {
    try {
        const { grade, subject } = req.query;
        let query = 'SELECT * FROM notes';
        let params = [];

        if (grade && subject) {
            query += ' WHERE grade = ? AND subject = ?';
            params = [grade, subject];
        } else if (grade) {
            query += ' WHERE grade = ?';
            params = [grade];
        }

        query += ' ORDER BY created_at DESC';

        const [rows] = await db.execute(query, params);
        res.json(rows);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server Error' });
    }
};

exports.createNote = async (req, res) => {
    try {
        const { grade, subject, content, type } = req.body;
        // If file uploaded, use the filename, otherwise null
        // Ensure image_url is fully accessible path or just filename
        // user prompt said "Upload Images", so we accept file.
        // If type is text, content is used.

        let image_url = null;
        if (req.file) {
            image_url = `/uploads/${req.file.filename}`;
        }

        // Logic validation?
        // If type is image but no file?

        const [result] = await db.execute(
            'INSERT INTO notes (grade, subject, content, image_url, type) VALUES (?, ?, ?, ?, ?)',
            [grade, subject, content, image_url, type]
        );

        res.status(201).json({ id: result.insertId, grade, subject, content, image_url, type });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server Error' });
    }
};
