const express = require("express");
const pool = require("../models/db");
const { loadProxiesFromFile } = require("../utils/proxyManager");

const router = express.Router();

// Get all proxies
router.get("/", async (req, res) => {
    try {
        const [proxies] = await pool.query("SELECT * FROM proxies");
        res.json(proxies);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Add a new proxy manually
router.post("/add", async (req, res) => {
    const { proxy } = req.body;
    if (!proxy) return res.status(400).json({ error: "Proxy is required." });

    try {
        await pool.query("INSERT INTO proxies (proxy) VALUES (?)", [proxy]);
        res.status(201).json({ message: "Proxy added successfully." });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Delete a proxy
router.delete("/:id", async (req, res) => {
    const { id } = req.params;

    try {
        await pool.query("DELETE FROM proxies WHERE id = ?", [id]);
        res.json({ message: "Proxy deleted successfully." });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Load proxies from TXT file
router.post("/load-file", async (req, res) => {
    try {
        await loadProxiesFromFile();
        res.json({ message: "Proxies loaded from file." });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

module.exports = router;