const express = require("express");
const cors = require("cors");
const pool = require("./models/db");
const accountsRoutes = require("./routes/accounts");
const tokenRoutes = require("./routes/token");
const proxyRoutes = require("./routes/proxies");
const { processReceiptUpload, processBatchUpload, processSingleUpload, getValidToken } = require("./utils/uploadReceipt");
const axios = require("axios");
const { HttpsProxyAgent } = require("https-proxy-agent");
const geoip = require("geoip-lite");

const app = express();
app.use(cors());
app.use(express.json());
app.use(express.static("public"));

const runningTasks = new Map();
const usedProxies = new Set();
const usedImages = new Set();

class AbortSignal {
    constructor() {
        this.aborted = false;
    }
    abort() {
        this.aborted = true;
    }
    throwIfAborted() {
        if (this.aborted) {
            throw new Error("Process aborted by user");
        }
    }
}

app.use("/accounts", accountsRoutes);
app.use("/token", tokenRoutes);
app.use("/proxies", proxyRoutes);

app.post("/upload-receipt/:accountId", async (req, res) => {
    const { accountId } = req.params;
    const { imagePath } = req.body;
    console.log(`[DEBUG] Received upload-receipt request for account ${accountId} with imagePath: ${imagePath}`);
    if (!imagePath) {
        console.log(`[DEBUG] Validation failed: Image path is required`);
        return res.status(400).json({ error: "Image path is required" });
    }
    try {
        const [account] = await pool.query("SELECT proxy FROM accounts WHERE id = ?", [accountId]);
        if (!account.length || !account[0].proxy) {
            console.log(`[DEBUG] No proxy assigned to account ${accountId}`);
            return res.status(400).json({ error: "No proxy assigned to account" });
        }
        const result = await processReceiptUpload(accountId, imagePath);
        if (result) {
            console.log(`[DEBUG] Receipt uploaded successfully for account ${accountId}`);
            res.json({ message: "Receipt uploaded successfully", result });
        } else {
            console.log(`[DEBUG] Receipt upload failed for account ${accountId}`);
            res.status(500).json({ error: "Receipt upload failed" });
        }
    } catch (error) {
        console.error(`[ERROR] Failed to upload receipt for account ${accountId}: ${error.message}`);
        res.status(500).json({ error: `Failed to upload receipt: ${error.message}` });
    }
});

app.post("/upload-batch/multiple", async (req, res) => {
    const { numAccounts } = req.body;
    console.log(`[DEBUG] Received batch request for up to ${numAccounts} simultaneous accounts`);
    if (!numAccounts || numAccounts <= 0) {
        console.log(`[DEBUG] Validation failed: Invalid number of accounts`);
        return res.status(400).json({ error: "Invalid number of accounts" });
    }
    try {
        // Fetch all eligible accounts
        const [allAccounts] = await pool.query(
            "SELECT id FROM accounts WHERE status IN ('idle', 'stopped') AND disabled = FALSE ORDER BY id ASC"
        );
        if (allAccounts.length === 0) {
            console.log(`[DEBUG] No eligible accounts available`);
            return res.status(404).json({ error: "No eligible accounts available" });
        }

        console.log(`[DEBUG] Total eligible accounts: ${allAccounts.length}`);

        // Create a queue of account IDs
        const accountQueue = allAccounts.map(a => a.id);
        const runningAccounts = new Set();

        // Function to start processing an account
        const startAccount = async (accountId) => {
            const signal = new AbortSignal();
            runningTasks.set(accountId, { abort: signal });
            runningAccounts.add(accountId);
            try {
                await processBatchUpload(accountId, signal, usedProxies, usedImages);
                console.log(`[DEBUG] Account ${accountId} completed successfully`);
            } catch (error) {
                console.error(`[ERROR] Task for account ${accountId} failed: ${error.message}`);
            } finally {
                runningTasks.delete(accountId);
                runningAccounts.delete(accountId);
                // Start next account if queue is not empty
                if (accountQueue.length > 0) {
                    const nextAccountId = accountQueue.shift();
                    console.log(`[DEBUG] Starting next account ${nextAccountId} from queue`);
                    startAccount(nextAccountId);
                }
            }
        };

        // Start the first 'numAccounts' accounts
        const initialAccounts = accountQueue.splice(0, Math.min(numAccounts, allAccounts.length));
        console.log(`[DEBUG] Starting initial batch of ${initialAccounts.length} accounts: ${initialAccounts.join(", ")}`);
        initialAccounts.forEach(startAccount);

        // Respond immediately, letting the process run in the background
        res.json({ message: `Batch upload started for ${allAccounts.length} accounts with ${numAccounts} running simultaneously` });

        // Log completion when all accounts are done (optional, for debugging)
        (async () => {
            while (runningAccounts.size > 0 || accountQueue.length > 0) {
                await new Promise(resolve => setTimeout(resolve, 1000));
            }
            console.log(`[DEBUG] Batch upload completed for all ${allAccounts.length} accounts`);
        })();
    } catch (error) {
        console.error(`[ERROR] Batch endpoint failed: ${error.message}`, error.stack);
        res.status(500).json({ error: `Batch process failed: ${error.message}` });
    }
});

app.post("/upload-batch/:accountId", async (req, res) => {
    const { accountId } = req.params;
    console.log(`[DEBUG] Received single account batch request for ID ${accountId}`);
    let account;
    try {
        [account] = await pool.query("SELECT proxy FROM accounts WHERE id = ?", [accountId]);
        if (!account.length) {
            console.log(`[DEBUG] Account ${accountId} not found`);
            return res.status(404).json({ error: "Account not found" });
        }
        if (!account[0].proxy) {
            console.log(`[DEBUG] No proxy assigned to account ${accountId}`);
            return res.status(400).json({ error: "No proxy assigned to account" });
        }

        const signal = new AbortSignal();
        runningTasks.set(accountId, { abort: signal });

        await processBatchUpload(accountId, signal, usedProxies, usedImages);
        runningTasks.delete(accountId);
        console.log(`[DEBUG] Batch upload process started for account ${accountId}`);
        res.json({ message: "Batch upload process started" });
    } catch (error) {
        console.error(`[ERROR] Single batch failed for account ${accountId}: ${error.message}`);
        runningTasks.delete(accountId);
        
        await pool.query("UPDATE accounts SET status = 'error' WHERE id = ?", [accountId]);
        await pool.query("INSERT INTO logs (account_id, log_message) VALUES (?, ?)", [accountId, `Batch upload failed: ${error.message}`]);

        if (account && account[0].proxy) {
            const [proxyRows] = await pool.query("SELECT retry_count FROM proxies WHERE proxy = ?", [account[0].proxy]);
            if (proxyRows.length > 0) {
                const retryCount = (proxyRows[0].retry_count || 0) + 1;
                await pool.query("UPDATE proxies SET retry_count = ?, status = ? WHERE proxy = ?", [retryCount, retryCount >= 3 ? 'failed' : 'active', account[0].proxy]);
                console.log(`[DEBUG] Updated proxy ${account[0].proxy} retry_count to ${retryCount}`);
            }
        }

        res.status(500).json({ error: `Single batch failed: ${error.message}` });
    }
});

app.post("/stop/:accountId", async (req, res) => {
    const { accountId } = req.params;
    console.log(`[DEBUG] Received stop request for account ${accountId}`);
    try {
        await pool.query("UPDATE accounts SET status = 'stopped' WHERE id = ?", [accountId]);
        const taskInfo = runningTasks.get(accountId);
        if (taskInfo) {
            taskInfo.abort.abort();
            console.log(`🛑 Signaled stop for account ${accountId}`);
        }
        res.json({ message: `Stopped account ${accountId}` });
    } catch (error) {
        console.error(`[ERROR] Failed to stop account ${accountId}: ${error.message}`);
        res.status(500).json({ error: `Failed to stop account: ${error.message}` });
    }
});

app.get("/proxies", async (req, res) => {
    console.log(`[DEBUG] Received request to fetch proxies`);
    try {
        const [proxies] = await pool.query(`
            SELECT p.id, p.proxy, p.status, p.check_status, p.country, p.assigned_to, p.last_checked, a.name AS account_name
            FROM proxies p
            LEFT JOIN accounts a ON p.assigned_to = a.id
        `);
        console.log(`[DEBUG] Fetched proxies: ${JSON.stringify(proxies)}`);
        res.json(proxies);
    } catch (error) {
        console.error(`Failed to fetch proxies: ${error.message}`);
        res.status(500).json({ error: `Failed to fetch proxies: ${error.message}` });
    }
});

app.get("/accounts", async (req, res) => {
    console.log(`[DEBUG] Received request to fetch accounts`);
    try {
        const [accounts] = await pool.query(`
            SELECT id, name, total_points, weekly_points, images_uploaded, images_rejected, run_duration
            FROM accounts
        `);
        console.log(`[DEBUG] Fetched accounts: ${JSON.stringify(accounts)}`);
        res.json(accounts);
    } catch (error) {
        console.error(`Failed to fetch accounts: ${error.message}`);
        res.status(500).json({ error: `Failed to fetch accounts: ${error.message}` });
    }
});

app.post("/proxies/add-bulk", async (req, res) => {
    let { proxies } = req.body;
    console.log(`[DEBUG] Received request to add bulk proxies: ${JSON.stringify(proxies)}`);
    if (!proxies) {
        console.log("No proxies provided in request.");
        return res.status(400).json({ error: "No proxies provided" });
    }
    if (typeof proxies === "string") {
        proxies = proxies.split("\n").map(p => p.trim()).filter(p => p);
    }
    try {
        console.log(`Adding ${proxies.length} proxies to database...`);
        for (const proxy of proxies) {
            await pool.query(
                "INSERT INTO proxies (proxy, status) VALUES (?, 'unused') ON DUPLICATE KEY UPDATE status = 'unused'",
                [proxy]
            );
        }
        console.log("Proxies added successfully.");
        res.json({ message: "Proxies added successfully" });
    } catch (error) {
        console.error(`Failed to add proxies: ${error.message}`);
        res.status(500).json({ error: `Failed to add proxies: ${error.message}` });
    }
});

app.post("/proxies/delete", async (req, res) => {
    const { proxyIds } = req.body;
    console.log(`[DEBUG] Received request to delete proxies: ${JSON.stringify(proxyIds)}`);
    if (!proxyIds || !Array.isArray(proxyIds) || proxyIds.length === 0) {
        console.log(`[DEBUG] Validation failed: No proxy IDs provided`);
        return res.status(400).json({ error: "No proxy IDs provided" });
    }
    try {
        await pool.query("DELETE FROM proxies WHERE id IN (?)", [proxyIds]);
        console.log(`Deleted ${proxyIds.length} proxies`);
        res.json({ message: `Deleted ${proxyIds.length} proxies` });
    } catch (error) {
        console.error(`Failed to delete proxies: ${error.message}`);
        res.status(500).json({ error: `Failed to delete proxies: ${error.message}` });
    }
});

app.get("/proxies/export", async (req, res) => {
    const { proxyIds } = req.query;
    console.log(`[DEBUG] Received request to export proxies: ${proxyIds || 'all'}`);
    try {
        let proxies;
        if (proxyIds) {
            proxies = await pool.query("SELECT proxy FROM proxies WHERE id IN (?)", [proxyIds.split(",").map(Number)]);
        } else {
            proxies = await pool.query("SELECT proxy FROM proxies");
        }
        console.log(`[DEBUG] Exported proxies: ${JSON.stringify(proxies[0])}`);
        res.json(proxies[0].map(p => p.proxy));
    } catch (error) {
        console.error(`Failed to export proxies: ${error.message}`);
        res.status(500).json({ error: `Failed to export proxies: ${error.message}` });
    }
});

app.post("/proxies/check", async (req, res) => {
    const { proxyId } = req.body;
    console.log(`[DEBUG] Received request to check proxy: ${proxyId}`);
    try {
        const [proxyRows] = await pool.query("SELECT proxy FROM proxies WHERE id = ?", [proxyId]);
        if (proxyRows.length === 0) {
            console.log(`[DEBUG] Proxy not found: ${proxyId}`);
            return res.status(404).json({ error: "Proxy not found" });
        }
        const proxy = proxyRows[0].proxy;
        console.log(`[DEBUG] Checking proxy ${proxy}...`);

        await pool.query("UPDATE proxies SET check_status = 'checking', last_checked = NOW() WHERE id = ?", [proxyId]);

        const maxRetries = 2;
        let attempt = 0;
        let result;

        while (attempt <= maxRetries) {
            try {
                const startTime = Date.now();
                const agent = new HttpsProxyAgent(proxy);
                const response = await axios.get("https://httpbin.org/ip", {
                    httpsAgent: agent,
                    timeout: 5000,
                    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"
                    }
                });

                if (response.status === 200 && response.data.origin) {
                    const ip = response.data.origin;
                    const geo = geoip.lookup(ip);
                    const country = geo ? geo.country : "Unknown";
                    const responseTime = Date.now() - startTime;
                    await pool.query(
                        "UPDATE proxies SET check_status = 'alive', country = ?, last_checked = NOW() WHERE id = ?",
                        [country, proxyId]
                    );
                    console.log(`[DEBUG] Proxy ${proxy} is alive, IP: ${ip}, country: ${country}, response time: ${responseTime}ms`);
                    result = { proxy, ip, country, working: true, responseTime };
                    break;
                } else {
                    throw new Error("Invalid response from proxy judge");
                }
            } catch (error) {
                attempt++;
                if (attempt > maxRetries) {
                    await pool.query("UPDATE proxies SET check_status = 'dead', last_checked = NOW() WHERE id = ?", [proxyId]);
                    console.log(`[DEBUG] Proxy ${proxy} failed after ${maxRetries} retries: ${error.message}`);
                    result = { proxyId, working: false, error: error.message };
                } else {
                    console.log(`[DEBUG] Proxy ${proxy} attempt ${attempt} failed: ${error.message}, retrying...`);
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
            }
        }

        res.json(result);
    } catch (error) {
        console.error(`Failed to check proxy ${proxyId}: ${error.message}`);
        await pool.query("UPDATE proxies SET check_status = 'dead', last_checked = NOW() WHERE id = ?", [proxyId]);
        res.status(500).json({ proxyId, working: false, error: error.message });
    }
});

app.post("/proxies/check-all", async (req, res) => {
    console.log(`[DEBUG] Received request to check all proxies`);
    try {
        const [proxies] = await pool.query("SELECT id, proxy FROM proxies WHERE status != 'failed'");
        console.log(`[DEBUG] Checking ${proxies.length} proxies...`);

        const results = await Promise.all(proxies.map(async ({ id, proxy }) => {
            await pool.query("UPDATE proxies SET check_status = 'checking', last_checked = NOW() WHERE id = ?", [id]);
            const maxRetries = 2;
            let attempt = 0;
            let result;

            while (attempt <= maxRetries) {
                try {
                    const startTime = Date.now();
                    const agent = new HttpsProxyAgent(proxy);
                    const response = await axios.get("https://httpbin.org/ip", {
                        httpsAgent: agent,
                        timeout: 5000,
                        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"
                        }
                    });

                    if (response.status === 200 && response.data.origin) {
                        const ip = response.data.origin;
                        const geo = geoip.lookup(ip);
                        const country = geo ? geo.country : "Unknown";
                        const responseTime = Date.now() - startTime;
                        await pool.query(
                            "UPDATE proxies SET check_status = 'alive', country = ?, last_checked = NOW() WHERE id = ?",
                            [country, id]
                        );
                        console.log(`[DEBUG] Proxy ${proxy} is alive, IP: ${ip}, country: ${country}, response time: ${responseTime}ms`);
                        result = { id, proxy, ip, country, working: true, responseTime };
                        break;
                    } else {
                        throw new Error("Invalid response from proxy judge");
                    }
                } catch (error) {
                    attempt++;
                    if (attempt > maxRetries) {
                        await pool.query("UPDATE proxies SET check_status = 'dead', last_checked = NOW() WHERE id = ?", [id]);
                        console.log(`[DEBUG] Proxy ${proxy} failed after ${maxRetries} retries: ${error.message}`);
                        result = { id, proxy, working: false, error: error.message };
                    } else {
                        console.log(`[DEBUG] Proxy ${proxy} attempt ${attempt} failed: ${error.message}, retrying...`);
                        await new Promise(resolve => setTimeout(resolve, 1000));
                    }
                }
            }
            return result;
        }));

        res.json(results);
    } catch (error) {
        console.error(`Failed to check all proxies: ${error.message}`);
        res.status(500).json({ error: `Failed to check all proxies: ${error.message}` });
    }
});

app.post("/proxies/assign", async (req, res) => {
    const { proxyId, accountId } = req.body;
    console.log(`[DEBUG] Received request to assign proxy ${proxyId} to account ${accountId}`);
    try {
        const [proxyRows] = await pool.query("SELECT proxy FROM proxies WHERE id = ?", [proxyId]);
        if (proxyRows.length === 0) {
            console.log(`[DEBUG] Proxy not found: ${proxyId}`);
            return res.status(404).json({ error: "Proxy not found" });
        }
        const proxy = proxyRows[0].proxy;

        const [accountRows] = await pool.query("SELECT name FROM accounts WHERE id = ?", [accountId]);
        if (accountRows.length === 0) {
            console.log(`[DEBUG] Account not found: ${accountId}`);
            return res.status(404).json({ error: "Account not found" });
        }

        const [historyRows] = await pool.query("SELECT account_id FROM proxy_history WHERE proxy = ? AND account_id != ?", [proxy, accountId]);
        if (historyRows.length > 0) {
            console.log(`[DEBUG] Proxy ${proxy} already used by another account`);
            return res.status(400).json({ error: `Proxy ${proxy} already used by another account` });
        }

        await pool.query("UPDATE accounts SET proxy = ? WHERE id = ?", [proxy, accountId]);
        await pool.query("UPDATE proxies SET assigned_to = ?, status = 'active' WHERE id = ?", [accountId, proxyId]);
        await pool.query("INSERT INTO proxy_history (proxy, account_id) VALUES (?, ?)", [proxy, accountId]);
        await pool.query("INSERT INTO logs (account_id, log_message) VALUES (?, ?)", [accountId, `Proxy ${proxy} assigned to account ${accountId}`]);
        console.log(`[DEBUG] Assigned proxy ${proxy} to account ${accountId}`);
        res.json({ message: `Proxy ${proxy} assigned to account ${accountId}` });
    } catch (error) {
        console.error(`Failed to assign proxy: ${error.message}`);
        res.status(500).json({ error: `Failed to assign proxy: ${error.message}` });
    }
});

app.post("/accounts/add", async (req, res) => {
    console.log(`[DEBUG] Received request to add account: ${JSON.stringify(req.body)}`);
    const { name, email, token, refresh_token, proxy: clientProxy } = req.body;
    if (!name || !email || !token || !refresh_token || name.trim() === "" || email.trim() === "" || token.trim() === "" || refresh_token.trim() === "") {
        console.log(`[DEBUG] Validation failed: Missing or empty fields (name, email, token, refresh_token)`);
        return res.status(400).json({ error: "All fields (name, email, token, refresh_token) must be non-empty" });
    }

    try {
        let selectedProxy = clientProxy && clientProxy.trim() !== "" ? clientProxy.trim() : null;
        if (!selectedProxy) {
            const [availableProxies] = await pool.query(`
                SELECT p.proxy 
                FROM proxies p 
                LEFT JOIN proxy_history ph ON p.proxy = ph.proxy 
                WHERE p.status = 'unused' 
                AND p.assigned_to IS NULL 
                AND ph.proxy IS NULL 
                LIMIT 1
            `);
            selectedProxy = availableProxies.length > 0 ? availableProxies[0].proxy : '';
        } else {
            const [historyRows] = await pool.query("SELECT account_id FROM proxy_history WHERE proxy = ?", [selectedProxy]);
            if (historyRows.length > 0) {
                console.log(`[DEBUG] Proxy ${selectedProxy} already used by another account`);
                return res.status(400).json({ error: `Proxy ${selectedProxy} already used by another account` });
            }
        }

        console.log(`[DEBUG] Selected proxy for new account: ${selectedProxy}`);

        const [result] = await pool.query(
            "INSERT INTO accounts (name, email, token, refresh_token, proxy, status, last_updated, total_points, disabled, images_uploaded, images_rejected, last_run_time, run_duration, weekly_points) VALUES (?, ?, ?, ?, ?, ?, NOW(), ?, ?, ?, ?, NULL, NULL, ?)",
            [name.trim(), email.trim(), token.trim(), refresh_token.trim(), selectedProxy, 'idle', 0, 0, 0, 0, 0]
        );

        if (selectedProxy && selectedProxy !== '') {
            await pool.query("UPDATE proxies SET assigned_to = ?, status = 'active' WHERE proxy = ?", [result.insertId, selectedProxy]);
            await pool.query("INSERT INTO proxy_history (proxy, account_id) VALUES (?, ?)", [selectedProxy, result.insertId]);
            await pool.query("INSERT INTO logs (account_id, log_message) VALUES (?, ?)", [result.insertId, `Proxy ${selectedProxy} assigned to new account ${result.insertId}`]);
            console.log(`[DEBUG] Proxy ${selectedProxy} assigned to account ${result.insertId}`);
        }

        console.log(`[DEBUG] Added account ${name} with ID ${result.insertId}`);
        res.json({ message: `Account ${name} added successfully`, id: result.insertId });
    } catch (error) {
        console.error(`[ERROR] Failed to add account: ${error.message}`);
        res.status(500).json({ error: `Failed to add account: ${error.message}` });
    }
});

app.get("/logs", async (req, res) => {
    const { accountId } = req.query;
    console.log(`[DEBUG] Received request to fetch logs${accountId ? ` for account ${accountId}` : ''}`);
    const query = accountId
        ? "SELECT * FROM logs WHERE account_id = ? ORDER BY created_at DESC"
        : "SELECT * FROM logs ORDER BY created_at DESC";
    try {
        const [logs] = await pool.query(query, [accountId].filter(Boolean));
        console.log(`[DEBUG] Fetched logs: ${JSON.stringify(logs)}`);
        res.json(logs);
    } catch (error) {
        console.error(`Failed to fetch logs: ${error.message}`);
        res.status(500).json({ error: `Failed to fetch logs: ${error.message}` });
    }
});

app.delete("/accounts/:id", async (req, res) => {
    const { id } = req.params;
    console.log(`[DEBUG] Received request to delete account ${id}`);
    try {
        await pool.query("DELETE FROM accounts WHERE id = ?", [id]);
        console.log(`[DEBUG] Account ${id} deleted`);
        res.json({ message: `Account ${id} deleted` });
    } catch (error) {
        console.error(`Failed to delete account ${id}: ${error.message}`);
        res.status(500).json({ error: `Failed to delete account: ${error.message}` });
    }
});

app.post("/accounts/disable", async (req, res) => {
    const { id, disabled } = req.body;
    console.log(`[DEBUG] Received request to ${disabled ? 'disable' : 'enable'} account ${id}`);
    try {
        await pool.query("UPDATE accounts SET disabled = ? WHERE id = ?", [disabled ? 1 : 0, id]);
        console.log(`[DEBUG] Account ${id} disable state updated to ${disabled}`);
        res.json({ message: `Account ${id} disable state updated` });
    } catch (error) {
        console.error(`Failed to update disable state for account ${id}: ${error.message}`);
        res.status(500).json({ error: `Failed to update disable state: ${error.message}` });
    }
});

app.put("/accounts/:id", async (req, res) => {
    const { id } = req.params;
    const { name, email, token, refresh_token } = req.body;
    console.log(`[DEBUG] Received request to update account ${id}: ${JSON.stringify(req.body)}`);
    try {
        await pool.query(
            "UPDATE accounts SET name = ?, email = ?, token = ?, refresh_token = ? WHERE id = ?",
            [name, email, token, refresh_token, id]
        );
        console.log(`[DEBUG] Account ${id} updated successfully`);
        res.json({ message: `Account ${id} updated successfully` });
    } catch (error) {
        console.error(`Failed to update account ${id}: ${error.message}`);
        res.status(500).json({ error: `Failed to update account: ${error.message}` });
    }
});

app.get("/accounts/:id", async (req, res) => {
    const { id } = req.params;
    console.log(`[DEBUG] Received request to fetch account ${id}`);
    try {
        const [accounts] = await pool.query("SELECT * FROM accounts WHERE id = ?", [id]);
        if (accounts.length === 0) {
            console.log(`[DEBUG] Account not found: ${id}`);
            return res.status(404).json({ error: "Account not found" });
        }
        console.log(`[DEBUG] Fetched account: ${JSON.stringify(accounts[0])}`);
        res.json(accounts[0]);
    } catch (error) {
        console.error(`Failed to fetch account ${id}: ${error.message}`);
        res.status(500).json({ error: `Failed to fetch account: ${error.message}` });
    }
});

const PORT = 5000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});