import { Router } from "express";
import fs from "fs";
import { getDatabase } from "../../database.js";
import { scanDirectory } from "../../scanner.js";
import { serverLogger } from "../../../utils/logger.js";
import { validateFilePath } from "../../../utils/security.js";
export function createLibraryRoutes(appState) {
    const router = Router();
    // Get configured libraries
    router.get("/libraries", (req, res)=>{
        const libraries = appState.getAllLibraries();
        res.json(libraries);
    });
    // Add new library
    router.post("/libraries", async (req, res)=>{
        const { path: libraryPath } = req.body;
        if (!libraryPath) {
            return res.status(400).json({
                error: "Path is required"
            });
        }
        // Validate path
        if (!validateFilePath(libraryPath, [
            "/"
        ])) {
            return res.status(400).json({
                error: "Invalid path"
            });
        }
        // Check if path exists
        if (!fs.existsSync(libraryPath)) {
            return res.status(400).json({
                error: "Path does not exist"
            });
        }
        // Check if it's a directory
        const stats = fs.statSync(libraryPath);
        if (!stats.isDirectory()) {
            return res.status(400).json({
                error: "Path must be a directory"
            });
        }
        try {
            appState.addLibrary(libraryPath);
            // Start scanning the new library
            const tracks = await scanDirectory(libraryPath, appState);
            res.json({
                success: true,
                library: libraryPath,
                tracksFound: tracks.length
            });
        } catch (error) {
            serverLogger.error("Failed to add library", {
                path: libraryPath,
                error
            });
            res.status(500).json({
                error: "Failed to add library",
                details: error instanceof Error ? error.message : "Unknown error"
            });
        }
    });
    // Remove library
    router.delete("/libraries/:index", (req, res)=>{
        const index = parseInt(req.params.index);
        const libraries = appState.getAllLibraries();
        if (isNaN(index) || index < 0 || index >= libraries.length) {
            return res.status(400).json({
                error: "Invalid library index"
            });
        }
        const library = libraries[index];
        appState.removeLibrary(library);
        res.json({
            success: true,
            removed: library
        });
    });
    // Scan specific library
    router.post("/libraries/:index/scan", async (req, res)=>{
        const index = parseInt(req.params.index);
        const libraries = appState.getAllLibraries();
        if (isNaN(index) || index < 0 || index >= libraries.length) {
            return res.status(400).json({
                error: "Invalid library index"
            });
        }
        const library = libraries[index];
        if (appState.scanInProgress) {
            return res.status(409).json({
                error: "Scan already in progress"
            });
        }
        try {
            appState.scanInProgress = true;
            const tracks = await scanDirectory(library, appState);
            appState.scanInProgress = false;
            res.json({
                success: true,
                library,
                tracksFound: tracks.length
            });
        } catch (error) {
            appState.scanInProgress = false;
            serverLogger.error("Library scan failed", {
                library,
                error
            });
            res.status(500).json({
                error: "Scan failed",
                details: error instanceof Error ? error.message : "Unknown error"
            });
        }
    });
    // Get library stats
    router.get("/libraries/:index/stats", async (req, res)=>{
        const index = parseInt(req.params.index);
        const libraries = appState.getAllLibraries();
        if (isNaN(index) || index < 0 || index >= libraries.length) {
            return res.status(400).json({
                error: "Invalid library index"
            });
        }
        const library = libraries[index];
        const db = await getDatabase();
        // Get count directly from database for accurate stats
        const countResult = db.db.prepare("SELECT COUNT(*) as count FROM tracks WHERE path LIKE ?").get(library + "%");
        // Get unique artists and albums count
        const artistsResult = db.db.prepare("SELECT COUNT(DISTINCT artist) as count FROM tracks WHERE path LIKE ? AND artist IS NOT NULL").get(library + "%");
        const albumsResult = db.db.prepare("SELECT COUNT(DISTINCT album) as count FROM tracks WHERE path LIKE ? AND album IS NOT NULL").get(library + "%");
        // Get total file size
        const sizeResult = db.db.prepare("SELECT SUM(size) as total FROM tracks WHERE path LIKE ?").get(library + "%");
        const stats = {
            path: library,
            tracks: countResult.count,
            trackCount: countResult.count,
            totalSize: sizeResult.total || 0,
            artists: artistsResult.count,
            albums: albumsResult.count,
            lastScan: appState.getLastSyncTimestamp(library)
        };
        res.json(stats);
    });
    return router;
}

//# sourceMappingURL=libraryRoutes.js.map