const express = require('express');
const Booru = require('booru');

const app = express();

app.use(express.json());

app.post('/booru', (req, res) => {

    const { booru, tags, random, limit } = req.body;

    // Validate input
    if (!booru || typeof booru !== 'string') {
        return res.status(400).json({ error: 'Invalid or missing "booru"' });
    }

    if (!tags || !Array.isArray(tags)) {
        return res.status(400).json({ error: 'Invalid or missing "tags"' });
    }

    if (!limit || typeof limit !== 'number') {
        return res.status(400).json({ error: 'Invalid or missing "limit"' });
    }

    if (typeof random !== 'boolean') {
        return res.status(400).json({ error: 'Invalid or missing "random"' });
    }

    Booru.search(booru, tags, { limit: limit, random: random })
        .then(posts => {
            res.json(posts);
        }).catch(function(rej) {
            console.log(rej);
            res.status(400).json({ error: 'Booru returned an error' });
          });
});

// Start the server
const PORT = 3456;
const HOST = '0.0.0.0'
app.listen(PORT, HOST, () => {
    console.log(`Server is running on http://${HOST}:${PORT}`);
});
