const fetch = require('node-fetch'); // Ensure node-fetch is available (backend usually has it or native fetch in node 18+)
const db = require('../db');

/**
 * Imports posts from a WordPress site REST API.
 * @param {string} wpApiUrl - Base URL for fetching posts (e.g. https://infoseclabs.io/wp-json/wp/v2/posts)
 * @param {number} userId - The internal user ID to assign as author.
 */
const importFromWordPress = async (wpApiUrl = 'https://infoseclabs.io/wp-json/wp/v2/posts', userId = 1) => {
    console.log(`Starting import from ${wpApiUrl}...`);
    let page = 1;
    let importedCount = 0;
    let hasMore = true;

    // Helper to get media URL if it's not embedded directly easily, 
    // but typically we might just grab what we can or need to fetch media separately.
    // Basic WP API response usually needs `?_embed` to get featured media details easily,
    // or we fetch strictly what is provided.
    // The user's goal is simplicity. Let's try to fetch with `_embed` to get images if possible.
    const urlWithEmbed = `${wpApiUrl}?_embed&per_page=20`;

    while (hasMore) {
        try {
            const response = await fetch(`${urlWithEmbed}&page=${page}`);
            if (!response.ok) {
                // If 400 bad request (often means page out of bounds), stop.
                if (response.status === 400) {
                    hasMore = false;
                    break;
                }
                throw new Error(`Failed to fetch WP posts: ${response.statusText}`);
            }

            const posts = await response.json();
            if (!Array.isArray(posts) || posts.length === 0) {
                hasMore = false;
                break;
            }

            for (const post of posts) {
                const title = post.title.rendered;
                const slug = post.slug;
                const content = post.content.rendered;
                const excerpt = post.excerpt.rendered;
                const createdAt = new Date(post.date).toISOString().slice(0, 19).replace('T', ' ');

                // Featured Image
                let featuredImage = null;
                if (post._embedded && post._embedded['wp:featuredmedia'] && post._embedded['wp:featuredmedia'][0]) {
                    featuredImage = post._embedded['wp:featuredmedia'][0].source_url;
                } else if (post.featured_media && !post._embedded) {
                    // If we didn't get embedded data but have an ID, we might skip strictly for speed 
                    // or better properly fetch it. For now, let's rely on _embed parameter working.
                    // Another fallback: check simple fields if custom API.
                    // Looking at user's JSON output previously: "jetpack_featured_media_url" might exist (not in standard, but common).
                    if (post.jetpack_featured_media_url) featuredImage = post.jetpack_featured_media_url;
                }

                // Insert or Update (Upsert based on slug)
                // Check if exists
                // Check if exists
                const { rows: existing } = await db.query('SELECT id FROM blog_posts WHERE slug = ?', [slug]);

                if (existing.length > 0) {
                    // Update
                    await db.query(
                        `UPDATE blog_posts 
                         SET title=?, content=?, excerpt=?, featured_image=?, updated_at=NOW(), status='published'
                         WHERE id=?`,
                        [title, content, excerpt, featuredImage, existing[0].id]
                    );
                    // console.log(`Updated: ${title}`);
                } else {
                    // Insert
                    await db.query(
                        `INSERT INTO blog_posts (title, slug, content, excerpt, featured_image, author_id, status, created_at)
                         VALUES (?, ?, ?, ?, ?, ?, 'published', ?)`,
                        [title, slug, content, excerpt, featuredImage, userId, createdAt]
                    );
                    // console.log(`Imported: ${title}`);
                }
                importedCount++;
            }

            console.log(`Page ${page} processed. Total so far: ${importedCount}`);
            page++;

        } catch (error) {
            console.error('Error during WP Import:', error);
            hasMore = false; // Stop on error
        }
    }

    return { imported: importedCount };
};

module.exports = importFromWordPress;
