import { Router } from "express";
import jwt from "jsonwebtoken";
import { serverLogger } from "../../../utils/serverLogger.js";
export function createStreamlineConnectRoute(appState) {
    const router = Router();
    // Simple connection endpoint - accepts JWT tokens from WAVE
    router.post("/connect", async (req, res)=>{
        try {
            const { access_token, refresh_token, user, streamline_url } = req.body;
            if (!access_token) {
                return res.status(400).json({
                    success: false,
                    error: "Missing required access token"
                });
            }
            // Use SOUND_JWT_SECRET for validation (shared with WAVE)
            const JWT_SECRET = process.env.SOUND_JWT_SECRET || process.env.JWT_SECRET;
            if (!JWT_SECRET) {
                serverLogger.error("JWT secret not configured - SOUND_JWT_SECRET or JWT_SECRET environment variable required");
                return res.status(500).json({
                    success: false,
                    error: "Server configuration error - JWT secret not set"
                });
            }
            try {
                // Decode without verification first to inspect the token
                const decoded = jwt.decode(access_token);
                // WAVE tokens have userId, email, username structure
                // Old tokens might have client_id
                const isWaveToken = decoded?.userId || decoded?.email;
                const isLegacyToken = decoded?.client_id === "sound-app";
                if (!isWaveToken && !isLegacyToken) {
                    serverLogger.warn("Invalid token structure", {
                        decoded
                    });
                    throw new Error("Invalid token format");
                }
                // Now verify the signature
                const verified = jwt.verify(access_token, JWT_SECRET);
                // Extract user info from token or request body
                const userId = verified.userId || user?.id;
                const userEmail = verified.email || user?.email;
                if (!userId || !userEmail) {
                    throw new Error("Missing user identification in token");
                }
                // Store the connection info in app state
                const connectionInfo = {
                    user_id: userId,
                    user_email: userEmail,
                    username: verified.username || user?.username,
                    display_name: verified.displayName || user?.display_name,
                    access_token,
                    refresh_token,
                    streamline_url: streamline_url || "https://streamline.club",
                    connected_at: new Date().toISOString()
                };
                // Save to app state (you might want to persist this)
                appState.streamlineConnection = connectionInfo;
                // Also store API key for future requests
                appState.setApiKey(access_token);
                serverLogger.info("Streamline connection established", {
                    user_id: userId,
                    email: userEmail
                });
                return res.json({
                    success: true,
                    message: "Successfully connected to Streamline",
                    server: {
                        name: "SOUND Music Server",
                        version: "1.0.0",
                        tracks: appState.getTotalTracks?.() || 0
                    }
                });
            } catch (error) {
                serverLogger.error("Invalid access token", error);
                return res.status(401).json({
                    success: false,
                    error: "Invalid access token"
                });
            }
        } catch (error) {
            serverLogger.error("Connection error", error);
            return res.status(500).json({
                success: false,
                error: "Failed to establish connection"
            });
        }
    });
    // Status endpoint to check connection
    router.get("/status", (req, res)=>{
        const connection = appState.streamlineConnection;
        if (!connection) {
            return res.json({
                connected: false
            });
        }
        // Verify token is still valid
        const JWT_SECRET = process.env.SOUND_JWT_SECRET || process.env.JWT_SECRET;
        if (!JWT_SECRET) {
            return res.json({
                connected: false,
                reason: "Server configuration error"
            });
        }
        try {
            jwt.verify(connection.access_token, JWT_SECRET);
            return res.json({
                connected: true,
                user: {
                    id: connection.user_id,
                    email: connection.user_email
                },
                connected_since: connection.connected_at
            });
        } catch  {
            // Token expired
            return res.json({
                connected: false,
                reason: "Token expired"
            });
        }
    });
    // Disconnect endpoint
    router.post("/disconnect", (req, res)=>{
        appState.streamlineConnection = null;
        serverLogger.info("Streamline connection disconnected");
        return res.json({
            success: true,
            message: "Disconnected from Streamline"
        });
    });
    return router;
}

//# sourceMappingURL=streamlineConnect.js.map