import { NextResponse } from 'next/server';
import fs from 'fs-extra';
import path from 'path';
import { addTorrent, recheckTorrent } from '@/lib/qbittorrent';
import { QbittorrentInjectResponse } 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 parentDir = path.dirname(albumPath);
        const albumDirName = path.basename(albumPath);

        // Logic to find the torrent file (similar to torrent creation route)
        let torrentPath = path.join(parentDir, `${albumDirName}.torrent`);

        if (!await fs.pathExists(torrentPath)) {
            // Try to find a recent torrent file if exact match fails
            const files = await fs.readdir(parentDir);
            const recentTorrent = (await Promise.all(files
                .filter(f => f.endsWith('.torrent'))
                .map(async f => {
                    const stat = await fs.stat(path.join(parentDir, f));
                    return { name: f, mtime: stat.mtimeMs };
                })
            ))
                .sort((a, b) => b.mtime - a.mtime)[0];

            if (recentTorrent) {
                torrentPath = path.join(parentDir, recentTorrent.name);
            } else {
                return NextResponse.json({ error: 'Torrent file not found. Please create it first.' }, { status: 404 });
            }
        }

        const torrentData = await fs.readFile(torrentPath);
        const filename = path.basename(torrentPath);

        // 1. Add torrent (paused)
        const hash = await addTorrent(torrentData, filename, 'RED');

        // 2. Trigger recheck
        await recheckTorrent(hash);

        const response: QbittorrentInjectResponse = { success: true, hash };
        return NextResponse.json(response);

    } catch (error) {
        console.error('Error injecting torrent:', error);
        const errorMessage = error instanceof Error ? error.message : String(error);
        return NextResponse.json({
            error: 'Failed to inject torrent',
            details: errorMessage
        }, { status: 500 });
    }
}
