import { NextResponse } from 'next/server';
import fs from 'fs-extra';
import path from 'path';
import { getOutputDir } from '@/lib/utils/paths';
import { copyDirRecursive } from '@/lib/utils/file-ops';
import { CopyResponse } from '@/types';

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 outputDir = getOutputDir();
        if (!outputDir) {
            return NextResponse.json({ error: 'OUTPUT_DIR not configured in .env.local' }, { status: 400 });
        }

        // Ensure output directory exists
        await fs.ensureDir(outputDir);

        const albumName = path.basename(albumPath);
        const destPath = path.join(outputDir, albumName);

        // Check if destination already exists
        if (await fs.pathExists(destPath)) {
            return NextResponse.json({ error: 'Album already exists in output directory' }, { status: 409 });
        }


        try {
            await fs.copy(albumPath, destPath);
        } catch (error) {
            const err = error as NodeJS.ErrnoException;
            if (err.code === 'EINVAL') {
                console.warn('fs-extra copy failed with EINVAL, attempting fallback to stream-based copy', error);
                // Fallback to custom stream-based copy to avoid copyfile syscall
                await copyDirRecursive(albumPath, destPath);
            } else {
                throw error;
            }
        }

        const response: CopyResponse = { success: true, destPath };
        return NextResponse.json(response);
    } catch (error) {
        console.error('Error copying album:', error);
        return NextResponse.json({ error: 'Failed to copy album' }, { status: 500 });
    }
}
