import { NextResponse } from 'next/server';
import fs from 'fs-extra';
import path from 'path';
import { sanitizeName, sanitizeAlbumName } from '@/lib/utils/sanitize';

export async function POST(request: Request) {
    try {
        const { albumPath } = await request.json();

        if (!albumPath || !(await fs.pathExists(albumPath))) {
            return NextResponse.json({ error: 'Invalid album path' }, { status: 400 });
        }

        const files = await fs.readdir(albumPath);

        // 1. Rename files
        for (const file of files) {
            const oldPath = path.join(albumPath, file);
            const stat = await fs.stat(oldPath);

            if (stat.isFile()) {
                const ext = path.extname(file);
                const name = path.basename(file, ext);
                const cleanName = sanitizeName(name) + ext;

                if (cleanName !== file) {
                    const newPath = path.join(albumPath, cleanName);
                    await fs.rename(oldPath, newPath);
                }
            }
        }

        // 2. Rename album folder
        const parentDir = path.dirname(albumPath);
        const oldDirName = path.basename(albumPath);
        const cleanDirName = sanitizeAlbumName(oldDirName);

        let newAlbumPath = albumPath;

        if (cleanDirName !== oldDirName) {
            newAlbumPath = path.join(parentDir, cleanDirName);
            await fs.rename(albumPath, newAlbumPath);
        }

        return NextResponse.json({
            success: true,
            newAlbumPath,
            message: 'Sanitization complete'
        });
    } catch (error) {
        console.error('Error sanitizing album:', error);
        return NextResponse.json({ error: 'Failed to sanitize album' }, { status: 500 });
    }
}
