import { Router } from "express";
import { lastFmService } from "../../lastFmService.js";
import { listenBrainzService } from "../../listenBrainzService.js";
import { serverLogger } from "../../../utils/logger.js";
const router = Router();
// Last.fm Routes
router.get("/lastfm/status", (req, res)=>{
    try {
        const status = lastFmService.getStatus();
        res.json(status);
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        serverLogger.error("Failed to get Last.fm status", {
            error: errorMessage
        });
        res.status(500).json({
            error: "Failed to get status"
        });
    }
});
router.post("/lastfm/import", async (req, res)=>{
    try {
        const { username, limit = 200 } = req.body;
        if (!username) {
            return res.status(400).json({
                error: "Username is required"
            });
        }
        // Start import in background
        const importPromise = lastFmService.importHistory(username, limit);
        // Return immediately
        res.json({
            success: true,
            message: `Starting import for ${username}. This may take a few minutes.`
        });
        // Handle import completion
        importPromise.then((result)=>{
            serverLogger.info("Last.fm import completed", result);
        }).catch((error)=>{
            serverLogger.error("Last.fm import failed", {
                error
            });
        });
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        serverLogger.error("Failed to start Last.fm import", {
            error: errorMessage
        });
        res.status(500).json({
            error: "Failed to start import"
        });
    }
});
router.post("/lastfm/import-loved", async (req, res)=>{
    try {
        const { username } = req.body;
        if (!username) {
            return res.status(400).json({
                error: "Username is required"
            });
        }
        const count = await lastFmService.importLovedTracks(username);
        res.json({
            success: true,
            count,
            message: `Updated ${count} tracks as loved`
        });
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        serverLogger.error("Failed to import loved tracks", {
            error: errorMessage
        });
        res.status(500).json({
            error: "Failed to import loved tracks"
        });
    }
});
router.get("/lastfm/user/:username", async (req, res)=>{
    try {
        const userInfo = await lastFmService.getUserInfo(req.params.username);
        // Always return 200 even if limited data
        res.json(userInfo);
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        serverLogger.error("Failed to get Last.fm user info", {
            error: errorMessage
        });
        // Return basic user info even on error
        res.json({
            name: req.params.username,
            realname: req.params.username,
            playcount: "N/A",
            registered: {
                "#text": "N/A"
            },
            country: "N/A",
            image: [
                {
                    "#text": ""
                }
            ],
            error: "Unable to fetch user info",
            limited: true
        });
    }
});
router.post("/lastfm/autosync", async (req, res)=>{
    try {
        const { enabled } = req.body;
        lastFmService.setAutoSync(enabled);
        res.json({
            success: true,
            autoSync: enabled
        });
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        serverLogger.error("Failed to set auto-sync", {
            error: errorMessage
        });
        res.status(500).json({
            error: "Failed to set auto-sync"
        });
    }
});
// OAuth authentication endpoints
router.post("/lastfm/auth/start", async (req, res)=>{
    try {
        const { token, authUrl } = await lastFmService.getAuthToken();
        res.json({
            success: true,
            token,
            authUrl,
            message: "Please authorize SOUND in your browser"
        });
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        serverLogger.error("Failed to start Last.fm auth", {
            error: errorMessage
        });
        res.status(500).json({
            error: errorMessage
        });
    }
});
router.post("/lastfm/auth/complete", async (req, res)=>{
    try {
        const { token } = req.body;
        if (!token) {
            return res.status(400).json({
                error: "Token is required"
            });
        }
        const { sessionKey, username } = await lastFmService.getSession(token);
        res.json({
            success: true,
            username,
            sessionKey,
            message: "Successfully connected to Last.fm"
        });
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        serverLogger.error("Failed to complete Last.fm auth", {
            error: errorMessage
        });
        res.status(500).json({
            error: "Failed to authenticate. Please make sure you authorized SOUND on Last.fm"
        });
    }
});
router.post("/lastfm/disconnect", async (req, res)=>{
    try {
        await lastFmService.disconnect();
        res.json({
            success: true,
            message: "Disconnected from Last.fm"
        });
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        serverLogger.error("Failed to disconnect Last.fm", {
            error: errorMessage
        });
        res.status(500).json({
            error: "Failed to disconnect"
        });
    }
});
// ListenBrainz Routes (already implemented, just moved here)
router.get("/listenbrainz/status", (req, res)=>{
    try {
        const status = listenBrainzService.getStatus();
        res.json(status);
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        serverLogger.error("Failed to get ListenBrainz status", {
            error: errorMessage
        });
        res.status(500).json({
            error: "Failed to get status"
        });
    }
});
router.post("/listenbrainz/configure", async (req, res)=>{
    try {
        const { userToken, username } = req.body;
        if (!userToken || !username) {
            return res.status(400).json({
                error: "User token and username are required"
            });
        }
        const success = await listenBrainzService.configure(userToken, username);
        if (success) {
            res.json({
                success: true,
                message: "ListenBrainz configured successfully"
            });
        } else {
            res.status(400).json({
                error: "Invalid token or configuration failed"
            });
        }
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        serverLogger.error("Failed to configure ListenBrainz", {
            error: errorMessage
        });
        res.status(500).json({
            error: "Failed to configure"
        });
    }
});
router.post("/listenbrainz/sync", async (req, res)=>{
    try {
        const hours = req.body.hours || 24;
        const synced = await listenBrainzService.syncRecentScrobbles(hours);
        res.json({
            success: true,
            synced,
            message: `Synced ${synced} scrobbles to ListenBrainz`
        });
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        serverLogger.error("Failed to sync to ListenBrainz", {
            error: errorMessage
        });
        res.status(500).json({
            error: "Failed to sync"
        });
    }
});
router.post("/listenbrainz/disable", async (req, res)=>{
    try {
        await listenBrainzService.disable();
        res.json({
            success: true,
            message: "ListenBrainz integration disabled"
        });
    } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        serverLogger.error("Failed to disable ListenBrainz", {
            error: errorMessage
        });
        res.status(500).json({
            error: "Failed to disable"
        });
    }
});
export default router;

//# sourceMappingURL=integrationsRoutes.js.map