import { NextRequest, NextResponse } from 'next/server';
import path from 'path';
import fs from 'fs/promises';

export async function GET(req: NextRequest): Promise<NextResponse> {
    const pathname = req.nextUrl.pathname; // /api/uploads/games/image.png
    const relativePath = pathname.replace(/^\/api\/uploads\//, ''); // games/image.png

    const filePath = path.join(process.cwd(), 'uploads', ...relativePath.split('/'));

    try {
        await fs.access(filePath);
        const fileBuffer = await fs.readFile(filePath);

        const ext = path.extname(filePath).slice(1).toLowerCase();
        const contentTypes: Record<string, string> = {
            jpg: 'image/jpeg',
            jpeg: 'image/jpeg',
            png: 'image/png',
            webp: 'image/webp',
            gif: 'image/gif',
        };

        return new NextResponse(fileBuffer, {
            status: 200,
            headers: {
                'Content-Type': contentTypes[ext] || 'application/octet-stream',
            },
        });
    } catch (err) {
        console.error('Файл не найден:', err);
        return new NextResponse('Not found', { status: 404 });
    }
}
