const express = require("express");
const router = express.Router();
const pool = require("../models/db");
const { refreshToken } = require("../utils/tokenManager");

// Route to refresh token for a single account
router.post("/refresh/:accountId", async (req, res) => {
    const { accountId } = req.params;

    try {
        // Fetch current refresh token from the database
        const [rows] = await pool.query("SELECT refresh_token FROM accounts WHERE id = ?", [accountId]);

        if (rows.length === 0) {
            return res.status(404).json({ error: "Account not found" });
        }

        const oldRefreshToken = rows[0].refresh_token;
        const result = await refreshToken(accountId, oldRefreshToken);

        if (result.success) {
            res.json({ message: "Token refreshed successfully", newToken: result.newToken });
        } else {
            res.status(500).json({ error: result.error });
        }
    } catch (error) {
        console.error("? Error refreshing token:", error);
        res.status(500).json({ error: "Internal server error" });
    }
});

module.exports = router;