import { Router } from "express";
import { getDatabase } from "../database.js";
import { getArtworkService } from "../artworkService.js";
const router = Router();
// Get all albums with pagination
router.get("/", (req, res)=>{
    const db = getDatabase();
    const artworkService = getArtworkService();
    // PERFORMANCE: Add pagination to prevent loading 5,000+ albums at once
    const page = parseInt(req.query.page) || 1;
    const limit = Math.min(parseInt(req.query.limit) || 100, 500); // Max 500 per page
    const offset = (page - 1) * limit;
    const sortBy = req.query.sort_by || "artist"; // artist, album, year, track_count
    const order = req.query.order === "desc" ? "DESC" : "ASC";
    // Validate sort field to prevent SQL injection
    const allowedSorts = [
        "artist",
        "album",
        "track_count",
        "total_duration"
    ];
    const safeSortBy = allowedSorts.includes(sortBy) ? sortBy : "artist";
    // Get total count for pagination metadata
    const totalResult = db.db.prepare(`
    SELECT COUNT(DISTINCT artist || '-' || album) as total
    FROM tracks
    WHERE album IS NOT NULL
  `).get();
    // Get unique albums with track counts (paginated)
    const albums = db.db.prepare(`
    SELECT
      artist,
      album,
      COUNT(*) as track_count,
      MIN(artwork_hash) as artwork_hash,
      SUM(duration) as total_duration,
      MIN(year) as year
    FROM tracks
    WHERE album IS NOT NULL
    GROUP BY artist, album
    ORDER BY ${safeSortBy} ${order}
    LIMIT ? OFFSET ?
  `).all(limit, offset);
    const transformedAlbums = albums.map((album)=>({
            id: `${album.artist}-${album.album}`,
            title: album.album,
            artist: album.artist,
            year: album.year,
            track_count: album.track_count,
            total_duration: album.total_duration,
            artwork_url: album.artwork_hash ? artworkService.getArtworkUrl(album.artwork_hash, "medium") : null
        }));
    // Calculate pagination metadata
    const totalPages = Math.ceil(totalResult.total / limit);
    const hasNextPage = page < totalPages;
    const hasPrevPage = page > 1;
    res.json({
        albums: transformedAlbums,
        pagination: {
            page,
            limit,
            total: totalResult.total,
            total_pages: totalPages,
            has_next: hasNextPage,
            has_prev: hasPrevPage,
            count: albums.length
        }
    });
});
// Get album details with tracks
router.get("/:artist/:album", (req, res)=>{
    const artist = decodeURIComponent(req.params.artist);
    const album = decodeURIComponent(req.params.album);
    const db = getDatabase();
    const artworkService = getArtworkService();
    // Get album info from artist_albums table
    const albumInfo = db.db.prepare(`
    SELECT * FROM artist_albums 
    WHERE artist = ? AND album = ?
  `).get(artist, album);
    // Get tracks for this album
    const tracks = db.getTracksByAlbum(artist, album);
    if (tracks.length === 0) {
        res.status(404).json({
            error: "Album not found"
        });
        return;
    }
    // Transform tracks
    const transformedTracks = tracks.map((track)=>({
            id: track.path,
            title: track.title,
            duration: track.duration,
            file_url: `/stream?path=${encodeURIComponent(track.path)}`,
            track_number: track.track_no ?? null,
            disc_number: track.disk_no ?? null
        }));
    // Get artwork from first track with artwork
    const trackWithArt = tracks.find((t)=>t.artwork_hash);
    res.json({
        id: `${artist}-${album}`,
        title: album,
        artist: artist,
        year: albumInfo?.year,
        track_count: tracks.length,
        total_duration: tracks.reduce((sum, t)=>sum + (t.duration || 0), 0),
        artwork_url: trackWithArt?.artwork_hash ? artworkService.getArtworkUrl(trackWithArt.artwork_hash, "large") : albumInfo?.album_art_url,
        tracks: transformedTracks
    });
});
// Search albums
router.get("/search", (req, res)=>{
    const query = req.query.q;
    if (!query) {
        res.status(400).json({
            error: "Query parameter required"
        });
        return;
    }
    const db = getDatabase();
    const artworkService = getArtworkService();
    const albums = db.db.prepare(`
    SELECT 
      artist,
      album,
      COUNT(*) as track_count,
      MIN(artwork_hash) as artwork_hash
    FROM tracks
    WHERE album LIKE ? AND album IS NOT NULL
    GROUP BY artist, album
    ORDER BY artist, album
    LIMIT 50
  `).all(`%${query}%`);
    const transformedAlbums = albums.map((album)=>({
            id: `${album.artist}-${album.album}`,
            title: album.album,
            artist: album.artist,
            track_count: album.track_count,
            artwork_url: album.artwork_hash ? artworkService.getArtworkUrl(album.artwork_hash, "medium") : null
        }));
    res.json({
        albums: transformedAlbums,
        count: albums.length
    });
});
export default router;

//# sourceMappingURL=albums.js.map