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

// Insertar nuevo anime
const insertAnime = async (req, res) => {
    const {userId, title, score, progress, status, type, imageUrl, totalEpisodes} = 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 anime WHERE userId = ? AND title = ?',
            [userId, title]
        );

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

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

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


// Obtener animes de un usuario (lista completa o paginada)
const getAnimesByUser = 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 anime WHERE userId = ?', [userId]);
            const [rows] = await db.execute('SELECT * FROM anime 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 anime WHERE userId = ?', [userId]);
            return res.json(rows);
        }
    } catch (error) {
        console.error('Error obteniendo animes:', error);
        res.status(500).json({error: 'Error al obtener animes'});
    }
};

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

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

    try {
        await db.execute(
            'UPDATE anime SET title = ?, score = ?, progress = ?, status = ?, type = ?, imageUrl = ?, totalEpisodes = ? WHERE id = ?',
            [title, score, progress, status, type, imageUrl, totalEpisodes || 12, id]
        );
        res.status(200).json({message: 'Anime actualizado correctamente'});
    } catch (error) {
        console.error('Error actualizando anime:', error);
        res.status(500).json({error: 'Error al actualizar anime'});
    }
};

const getAnimesByUserAndStatus = async (req, res) => {
    const {userId, status} = req.params;
    try {
        const [rows] = await db.execute(
            'SELECT * FROM anime WHERE userId = ? AND status = ? ORDER BY id DESC',
            [userId, status]
        );
        res.json(rows);
    } catch (err) {
        res.status(500).json({error: 'Error al obtener animes'});
    }
};

const getAiringAnime = async (req, res) => {
    try {
        const [rows] = await db.execute(
            'SELECT * FROM anime WHERE status = "airing" ORDER BY id DESC LIMIT 20'
        );
        res.json(rows);
    } catch (err) {
        res.status(500).json({error: 'Error al obtener airing'});
    }
};


module.exports = {
    insertAnime,
    getAnimesByUser,
    deleteAnime,
    updateAnime,
    getAnimesByUserAndStatus,
    getAiringAnime
};
