import { NextResponse } from 'next/server';

export async function GET() {
    try {
        const res = await fetch('https://www.pinterest.com/irooflk/feed.rss', {
            next: { revalidate: 3600 } // Cache the response for 1 hour to prevent rate limits
        });
        
        if (!res.ok) {
            return NextResponse.json({ success: false, error: 'Failed to fetch RSS feed' }, { status: res.status });
        }
        
        const xml = await res.text();
        const items = [];
        const itemRegex = /<item>([\s\S]*?)<\/item>/g;
        let match;
        
        while ((match = itemRegex.exec(xml)) !== null) {
            const content = match[1];
            
            // Extract Title
            const titleMatch = content.match(/<title>([\s\S]*?)<\/title>/);
            const title = titleMatch ? titleMatch[1].trim() : '';
            
            // Extract Link
            const linkMatch = content.match(/<link>([\s\S]*?)<\/link>/);
            const link = linkMatch ? linkMatch[1].trim() : '';
            
            // Extract Image from <description>
            const descMatch = content.match(/<description>([\s\S]*?)<\/description>/);
            let image = '';
            if (descMatch) {
                const desc = descMatch[1];
                const imgMatch = desc.match(/src=&quot;(.*?)&quot;/);
                if (imgMatch) {
                    image = imgMatch[1];
                }
            }
            
            // Convert to high-res Pinterest image (564x is standard large)
            let highResImage = image;
            if (image.includes('/236x/')) {
                highResImage = image.replace('/236x/', '/564x/');
            }
            
            // Clean title (sometimes it contains HTML entities or extra hashtags)
            const cleanTitle = title
                .replace(/&amp;/g, '&')
                .replace(/&lt;/g, '<')
                .replace(/&gt;/g, '>')
                .replace(/&quot;/g, '"');

            items.push({
                title: cleanTitle,
                link,
                image: highResImage
            });
        }
        
        return NextResponse.json({ success: true, pins: items });
    } catch (error: any) {
        console.error('Pinterest API error:', error);
        return NextResponse.json({ success: false, error: error.message }, { status: 500 });
    }
}
