import { Router } from "express";
import { serverLogger } from "../../utils/serverLogger.js";
import { getDatabase } from "../database.js";
import { playerWebSocket } from "../playerWebSocket.js";
import { getUserByApiKey, hasFamilySharingTables } from "../migrations/addFamilySharing.js";
/**
 * Get user from API key in request
 */ function getUserFromRequest(req) {
    const db = getDatabase();
    if (!db?.db || !hasFamilySharingTables(db.db)) {
        return null;
    }
    const apiKey = req.headers["x-api-key"] || req.query.api_key || req.query.key;
    if (!apiKey) return null;
    const user = getUserByApiKey(db.db, apiKey);
    return user ? {
        id: user.id,
        name: user.name
    } : null;
}
/**
 * Create play history routes
 * Handles recording and retrieving playback history for WAVE integration
 */ export function createPlayHistoryRoutes() {
    const router = Router();
    /**
   * Record a play event
   * POST /api/plays
   *
   * Now includes user_id from authenticated API key for per-user history
   */ router.post("/", (req, res)=>{
        serverLogger.debug("/api/plays endpoint hit");
        const { album, artist, track, artwork, context, duration_seconds, track_path } = req.body;
        const refId = req.body.ref_id ?? req.body.refId ?? null;
        if (!album || !artist) {
            return res.status(400).json({
                error: "album and artist are required"
            });
        }
        // Get user from API key (if family sharing is enabled)
        const user = getUserFromRequest(req);
        // Save to database
        try {
            const db = getDatabase();
            if (db?.db) {
                // Check if user_id column exists (family sharing enabled)
                const hasUserIdColumn = hasFamilySharingTables(db.db);
                const timestamp = Date.now();
                // Check if stats columns exist (duration_seconds, track_path)
                let hasStatsColumns = false;
                try {
                    const tableInfo = db.db.prepare("PRAGMA table_info(wave_play_history)").all();
                    hasStatsColumns = tableInfo.some((col)=>col.name === "duration_seconds");
                } catch  {
                    hasStatsColumns = false;
                }
                if (hasUserIdColumn && user) {
                    // Insert with user_id for per-user history
                    if (hasStatsColumns) {
                        const stmt = db.db.prepare(`
              INSERT INTO wave_play_history (album, artist, track, artwork, context, timestamp, user_id, duration_seconds, track_path, ref_id)
              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            `);
                        stmt.run(album, artist, track || null, artwork || null, context || "track", timestamp, user.id, duration_seconds || null, track_path || null, refId);
                    } else {
                        const stmt = db.db.prepare(`
              INSERT INTO wave_play_history (album, artist, track, artwork, context, timestamp, user_id, ref_id)
              VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            `);
                        stmt.run(album, artist, track || null, artwork || null, context || "track", timestamp, user.id, refId);
                    }
                    serverLogger.info(`Play recorded for ${user.name}: ${artist} - ${album}${duration_seconds ? ` (${duration_seconds}s)` : ""}`);
                } else {
                    // Legacy insert without user_id
                    if (hasStatsColumns) {
                        const stmt = db.db.prepare(`
              INSERT INTO wave_play_history (album, artist, track, artwork, context, timestamp, duration_seconds, track_path, ref_id)
              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            `);
                        stmt.run(album, artist, track || null, artwork || null, context || "track", timestamp, duration_seconds || null, track_path || null, refId);
                    } else {
                        const stmt = db.db.prepare(`
              INSERT INTO wave_play_history (album, artist, track, artwork, context, timestamp, ref_id)
              VALUES (?, ?, ?, ?, ?, ?, ?)
            `);
                        stmt.run(album, artist, track || null, artwork || null, context || "track", timestamp, refId);
                    }
                    serverLogger.info(`Play recorded: ${artist} - ${album}${duration_seconds ? ` (${duration_seconds}s)` : ""}`);
                }
                // Broadcast play.recorded event to all connected clients for cross-device sync
                // Include user info so clients can filter by user
                playerWebSocket.broadcast({
                    type: "play.recorded",
                    data: {
                        album,
                        artist,
                        track: track || null,
                        artwork: artwork || null,
                        context: context || "track",
                        timestamp,
                        user_id: user?.id || null,
                        user_name: user?.name || null,
                        duration_seconds: duration_seconds || null,
                        ref_id: refId
                    }
                }, "plays");
                res.json({
                    success: true,
                    user_id: user?.id || null
                });
            } else {
                res.status(500).json({
                    error: "Database not available"
                });
            }
        } catch (error) {
            serverLogger.error("Failed to record play:", error);
            res.status(500).json({
                error: "Failed to save play"
            });
        }
    });
    /**
   * Get recent plays
   * GET /api/plays/recent
   *
   * Returns play history filtered by the authenticated user's API key.
   * Each user only sees their own recently played albums.
   */ router.get("/recent", (req, res)=>{
        try {
            const db = getDatabase();
            if (!db?.db) {
                return res.json({
                    albums: []
                });
            }
            const limit = parseInt(req.query.limit) || 50;
            // Get user from API key for filtering
            const user = getUserFromRequest(req);
            const hasUserIdColumn = hasFamilySharingTables(db.db);
            // Debug logging for family sharing
            const apiKey = req.headers["x-api-key"] || req.query.api_key || req.query.key;
            serverLogger.info("[PlayHistory] /recent request", {
                hasApiKey: !!apiKey,
                apiKeyPrefix: apiKey ? apiKey.substring(0, 10) + "..." : "none",
                foundUser: user ? {
                    id: user.id,
                    name: user.name
                } : null,
                hasFamilySharing: hasUserIdColumn
            });
            let results;
            if (hasUserIdColumn && user) {
                // Filter by user_id for per-user history
                serverLogger.info("[PlayHistory] Filtering by user_id:", user.id);
                const stmt = db.db.prepare(`
          SELECT
            album,
            artist,
            MAX(artwork) as artwork,
            MAX(timestamp) as last_played,
            COUNT(*) as play_count,
            MAX(context) as context,
            MAX(ref_id) as ref_id
          FROM wave_play_history
          WHERE user_id = ?
          GROUP BY album, artist
          ORDER BY last_played DESC
          LIMIT ?
        `);
                results = stmt.all(user.id, limit);
                serverLogger.info("[PlayHistory] Found", results.length, "albums for user", user.name);
            } else if (hasUserIdColumn) {
                // Family sharing enabled but no user identified - return plays without user_id
                // (legacy plays before family sharing was enabled)
                const stmt = db.db.prepare(`
          SELECT
            album,
            artist,
            MAX(artwork) as artwork,
            MAX(timestamp) as last_played,
            COUNT(*) as play_count,
            MAX(context) as context,
            MAX(ref_id) as ref_id
          FROM wave_play_history
          WHERE user_id IS NULL
          GROUP BY album, artist
          ORDER BY last_played DESC
          LIMIT ?
        `);
                results = stmt.all(limit);
            } else {
                // Legacy mode - no family sharing, return all plays
                const stmt = db.db.prepare(`
          SELECT
            album,
            artist,
            MAX(artwork) as artwork,
            MAX(timestamp) as last_played,
            COUNT(*) as play_count,
            MAX(context) as context,
            MAX(ref_id) as ref_id
          FROM wave_play_history
          GROUP BY album, artist
          ORDER BY last_played DESC
          LIMIT ?
        `);
                results = stmt.all(limit);
            }
            // Look up artwork_hash from tracks table for each album
            const albums = results.map((row)=>{
                let artworkHash = null;
                let fullArtworkUrl = null;
                // First try the artwork stored in play history (might be a hash, URL, or artist-image marker)
                if (row.artwork) {
                    // Check for artist-image marker format (e.g., "artist-image:AFI")
                    if (row.artwork.startsWith('artist-image:')) {
                        // Extract artist name and return as relative URL
                        // This avoids storing stale tunnel URLs in the database
                        const artistName = row.artwork.replace('artist-image:', '');
                        fullArtworkUrl = `/api/artist-image/${encodeURIComponent(artistName)}`;
                    } else if (row.artwork.startsWith('http') || row.artwork.startsWith('/')) {
                        // If it's a URL, try to extract the hash from it
                        const match = row.artwork.match(/\/artwork\/([a-f0-9]+)/);
                        if (match && match[1]) {
                            artworkHash = match[1];
                        } else if (row.artwork.includes('/artist-image/')) {
                            // For legacy full URLs with artist-image, extract artist name
                            // and return as relative URL to avoid stale tunnel URLs
                            const artistMatch = row.artwork.match(/\/artist-image\/([^?]+)/);
                            if (artistMatch && artistMatch[1]) {
                                fullArtworkUrl = `/api/artist-image/${artistMatch[1]}`;
                            }
                        }
                    // If we can't extract a hash from the URL, leave artworkHash as null
                    // and fall through to the tracks table lookup below
                    } else {
                        // It's already a raw hash
                        artworkHash = row.artwork;
                    }
                }
                // If no artwork in play history, look up from tracks table
                if (!artworkHash) {
                    try {
                        const trackStmt = db.db.prepare(`
              SELECT artwork_hash
              FROM tracks
              WHERE album = ? AND artist = ?
              AND artwork_hash IS NOT NULL
              LIMIT 1
            `);
                        const track = trackStmt.get(row.album, row.artist);
                        if (track?.artwork_hash) {
                            artworkHash = track.artwork_hash;
                        }
                    } catch (err) {
                        serverLogger.debug(`Failed to look up artwork for ${row.artist} - ${row.album}:`, err);
                    }
                }
                return {
                    album: row.album,
                    artist: row.artist,
                    // Return full URL for artist images (Currents), otherwise raw hash
                    artwork: fullArtworkUrl || artworkHash,
                    last_played: new Date(row.last_played).toISOString(),
                    play_count: row.play_count,
                    context: row.context || "track",
                    ref_id: row.ref_id ?? null
                };
            });
            res.json({
                albums
            });
        } catch (error) {
            serverLogger.error("Failed to get recent plays:", error);
            res.json({
                albums: []
            });
        }
    });
    serverLogger.info("Play history routes registered");
    return router;
}

//# sourceMappingURL=playHistoryRoutes.js.map