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

// Insertar nuevo manga
const insertManga = async (req, res) => {
    const {userId, title, score, progress, status, type, imageUrl, totalChapters} = req.body;

    if (!userId || !title || !status || !type || !imageUrl) {
        return res.status(400).json({error: 'Faltan campos obligatorios'});
    }

    try {
        // Verificar si ya existe
        const [existing] = await db.execute(
            'SELECT id FROM manga WHERE userId = ? AND title = ?',
            [userId, title]
        );

        if (existing.length > 0) {
            return res.status(409).json({error: 'Este manga ya está en tu lista'});
        }

        await db.execute(
            'INSERT INTO manga (userId, title, score, progress, status, type, imageUrl, totalChapters) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
            [userId, title, score || 0, progress || 0, status, type, imageUrl, totalChapters || 12]
        );

        res.status(200).json({message: 'Manga añadido correctamente'});
    } catch (error) {
        console.error('Error insertando manga:', error);
        res.status(500).json({error: 'Error al insertar manga'});
    }
};


// Obtener mangas de un usuario (lista completa o paginada)
const getMangaByUser = async (req, res) => {
    const {userId} = req.params;
    const page = parseInt(req.query.page);
    const size = parseInt(req.query.size);

    try {
        if (!isNaN(page) && !isNaN(size)) {
            const offset = (page - 1) * size;
            const [[{total}]] = await db.execute('SELECT COUNT(*) AS total FROM manga WHERE userId = ?', [userId]);
            const [rows] = await db.execute('SELECT * FROM manga WHERE userId = ? LIMIT ? OFFSET ?', [userId, size, offset]);

            return res.json({
                data: rows,
                total,
                page,
                hasNextPage: offset + rows.length < total
            });
        } else {
            const [rows] = await db.execute('SELECT * FROM manga WHERE userId = ?', [userId]);
            return res.json(rows);
        }
    } catch (error) {
        console.error('Error obteniendo mangas:', error);
        res.status(500).json({error: 'Error al obtener mangas'});
    }
};

const deleteManga = async (req, res) => {
    const {id} = req.params;
    try {
        await db.execute('DELETE FROM manga WHERE id = ?', [id]);
        res.status(200).json({message: 'Manga eliminado correctamente'});
    } catch (error) {
        console.error('Error eliminando manga:', error);
        res.status(500).json({error: 'Error al eliminar manga'});
    }
};

const updateManga = async (req, res) => {
    const {id} = req.params;
    const {title, score, progress, status, type, imageUrl, totalChapters} = req.body;

    try {
        await db.execute(
            'UPDATE manga SET title = ?, score = ?, progress = ?, status = ?, type = ?, imageUrl = ?, totalChapters = ? WHERE id = ?',
            [title, score, progress, status, type, imageUrl, totalChapters || 12, id]
        );
        res.status(200).json({message: 'Manga actualizado correctamente'});
    } catch (error) {
        console.error('Error actualizando manga:', error);
        res.status(500).json({error: 'Error al actualizar manga'});
    }
};
const getMangaByUserAndStatus = async (req, res) => {
    const {userId, status} = req.params;
    try {
        const [rows] = await db.execute(
            'SELECT * FROM manga WHERE userId = ? AND status = ? ORDER BY id DESC',
            [userId, status]
        );
        res.json(rows);
    } catch (err) {
        res.status(500).json({error: 'Error al obtener mangas'});
    }
};


module.exports = {
    insertManga,
    getMangaByUser,
    deleteManga,
    updateManga,
    getMangaByUserAndStatus
};
