import { NextResponse } from 'next/server';

const FEED_URL = 'https://www.pinterest.com/irooflk/feed.rss';
const MAX_PINS = 50;

interface Pin {
    title: string;
    link: string;
    image: string;
}

const decodeEntities = (value: string) =>
    value
        .replace(/&quot;/g, '"')
        .replace(/&#39;|&apos;/g, "'")
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&#(\d+);/g, (_, code) => String.fromCharCode(Number(code)))
        .replace(/&amp;/g, '&');

// Read a tag's text, unwrapping CDATA if present.
const readTag = (xml: string, tag: string) => {
    const match = xml.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`));
    if (!match) return '';
    const cdata = match[1].match(/^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/);
    return (cdata ? cdata[1] : match[1]).trim();
};

// Only pass through https URLs on Pinterest's own domains, since they end up in href/src.
const isPinterestUrl = (value: string, hosts: RegExp) => {
    try {
        const url = new URL(value);
        return url.protocol === 'https:' && hosts.test(url.hostname);
    } catch {
        return false;
    }
};

const parseFeed = (xml: string): Pin[] => {
    const pins: Pin[] = [];
    const itemRegex = /<item>([\s\S]*?)<\/item>/g;
    let match;

    while ((match = itemRegex.exec(xml)) !== null && pins.length < MAX_PINS) {
        const content = match[1];
        const title = decodeEntities(readTag(content, 'title'));
        const link = decodeEntities(readTag(content, 'link'));
        // The pin image lives inside the (entity-encoded) HTML description.
        const description = decodeEntities(readTag(content, 'description'));
        const image = (description.match(/<img[^>]+src="([^"]+)"/) || [])[1] || '';

        if (!isPinterestUrl(link, /(^|\.)pinterest\.[a-z.]+$/) || !isPinterestUrl(image, /(^|\.)pinimg\.com$/)) {
            continue;
        }

        // Convert to high-res Pinterest image (564x is standard large)
        pins.push({ title, link, image: image.replace('/236x/', '/564x/') });
    }

    return pins;
};

export async function GET() {
    try {
        const res = await fetch(FEED_URL, {
            next: { revalidate: 3600 } // Cache the response for 1 hour to prevent rate limits
        });

        if (!res.ok) {
            console.error('Pinterest API error: feed responded with', res.status);
            return NextResponse.json({ success: false, error: 'Failed to fetch feed' }, { status: 502 });
        }

        const pins = parseFeed(await res.text());
        return NextResponse.json(
            { success: true, pins },
            { headers: { 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400' } }
        );
    } catch (error) {
        console.error('Pinterest API error:', error);
        return NextResponse.json({ success: false, error: 'Failed to fetch feed' }, { status: 500 });
    }
}
