import { NextResponse } from 'next/server';
import fs from 'fs-extra';
import path from 'path';
import { getWatchPath, ensureWatchDir } from '@/lib/utils/paths';

export async function GET() {
    try {
        const watchPath = await ensureWatchDir();
        const entries = await fs.readdir(watchPath, { withFileTypes: true });

        const albums = await Promise.all(
            entries
                .filter((entry) => entry.isDirectory())
                .map(async (entry) => {
                    const fullPath = path.join(watchPath, entry.name);

                    let coverPath: string | null = null;
                    try {
                        const files = await fs.readdir(fullPath);
                        const imageFiles = files.filter(f => /\.(jpg|jpeg|png)$/i.test(f));

                        // Priority 1: cover.jpg/jpeg/png
                        const explicitCover = imageFiles.find(f => /^cover\.(jpg|jpeg|png)$/i.test(f));

                        if (explicitCover) {
                            coverPath = path.join(fullPath, explicitCover);
                        } else if (imageFiles.length > 0) {
                            // Priority 2: Random image
                            coverPath = path.join(fullPath, imageFiles[0]);
                        }
                    } catch (e) {
                        // Ignore errors reading directory
                    }

                    return {
                        name: entry.name,
                        path: fullPath,
                        hasCover: !!coverPath,
                        coverPath
                    };
                })
        );

        return NextResponse.json({ albums });
    } catch (error) {
        console.error('Error scanning watch folder:', error);
        return NextResponse.json({ error: 'Failed to scan watch folder' }, { status: 500 });
    }
}
