const express = require('express');
const axios = require('axios');
const cheerio = require('cheerio');
const router = express.Router();

const targetUrl = process.env.TARGET_URL;

router.post('/bookmark-action', async (req, res) => {
    const { comicPath } = req.body;
    if (!comicPath) {
        return res.status(400).send({ message: 'URL komik tidak ditemukan.', status: 'error' });
    }

    const fullUrl = `${targetUrl}${comicPath}`;

    try {
        const response = await axios.get(fullUrl, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'Cookie': req.headers.cookie || ''
            }
        });

        const $ = cheerio.load(response.data);
        const bookmarkButton = $('#bookmark');

        if (bookmarkButton.length) {
            return res.status(200).send({
                message: 'Aksi bookmark berhasil diproses di terminal.',
                status: 'success'
            });
        } else {
            return res.status(404).send({ message: 'Tombol bookmark tidak ditemukan di halaman.', status: 'error' });
        }
    } catch (error) {
        res.status(500).send({ message: 'Gagal melakukan aksi bookmark.', status: 'error' });
    }
});

module.exports = router;