const db = require('../db');
const importFromWordPress = require('../services/wordpressImport');
const { generateBlogSeo, generateBlogTitle, enhanceBlogContent } = require('../utils/aiService');

// POST /api/admin/blog/generate-seo
exports.generateSeo = async (req, res) => {
    try {
        const { title, content } = req.body;
        if (!title && !content) {
            return res.status(400).json({ message: 'Title or content required' });
        }

        // Get AI Settings (Fetch by category to match server.js logic)
        const result = await db.query("SELECT `key`, value FROM system_settings WHERE category = 'ai_integration'");
        let settings = {};
        
        result.rows.forEach(row => {
            try { settings[row.key] = JSON.parse(row.value); } 
            catch(e) { settings[row.key] = row.value; }
        });

        // Handle case where it might be stored as a single JSON object under 'ai_integration' key (fallback)
        if (Object.keys(settings).length === 0) {
             const keyResult = await db.query("SELECT value FROM system_settings WHERE `key` = 'ai_integration'");
             if (keyResult.rows.length > 0) {
                 try { settings = JSON.parse(keyResult.rows[0].value); } catch(e) {}
             }
        }

        // Clean up string values (sometimes stored with extra quotes)
        if (settings.ai_api_key && typeof settings.ai_api_key === 'string') {
            settings.ai_api_key = settings.ai_api_key.replace(/^"|"$/g, '');
        }

        if (!settings.ai_api_key) {
            console.error('AI API Key missing in settings:', settings);
            return res.status(500).json({ message: 'AI API Key not configured' });
        }

        const seoData = await generateBlogSeo(title || '', content || '', settings.ai_api_key);
        res.json(seoData);
    } catch (error) {
        console.error('SEO Generation Error:', error);
        res.status(500).json({ message: error.message || 'Failed to generate SEO' });
    }
};

// GET /api/blog (Public) - List published posts
exports.getPosts = async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const offset = (page - 1) * limit;
        const category = req.query.category || null;

        // Build query with optional category filter
        let whereClause = "status = 'published'";
        const params = [];
        
        if (category && category !== 'all') {
            whereClause += " AND category = ?";
            params.push(category);
        }

        const { rows: limitRows } = await db.query(
            `SELECT id, title, slug, excerpt, featured_image, category, created_at FROM blog_posts WHERE ${whereClause} ORDER BY created_at DESC LIMIT ${limit} OFFSET ${offset}`,
            params
        );
        const posts = limitRows;

        // Count for pagination
        const { rows: countResult } = await db.query(
            `SELECT COUNT(*) as total FROM blog_posts WHERE ${whereClause}`,
            params
        );
        const total = countResult[0].total;

        // Get all unique categories for filter tabs
        const { rows: categoryRows } = await db.query(
            "SELECT DISTINCT category FROM blog_posts WHERE status = 'published' AND category IS NOT NULL ORDER BY category"
        );
        const categories = categoryRows.map(r => r.category);

        res.json({ posts, total, page, pages: Math.ceil(total / limit), categories });
    } catch (error) {
        console.error('Get Posts Error:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

// GET /api/blog/:slug (Public) - Get single post
exports.getPostBySlug = async (req, res) => {
    try {
        const { slug } = req.params;
        const { rows: posts } = await db.query(
            "SELECT * FROM blog_posts WHERE slug = ? AND status = 'published'",
            [slug]
        );

        if (posts.length === 0) {
            return res.status(404).json({ message: 'Post not found' });
        }

        res.json(posts[0]);
    } catch (error) {
        console.error('Get Post Error:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

// POST /api/admin/blog/import (Admin) - Import from local JSON file
exports.importPosts = async (req, res) => {
    try {
        const fs = require('fs');
        const path = require('path');
        
        const jsonPath = path.join(process.cwd(), 'Infoseclabs_Blogs.json');
        
        if (!fs.existsSync(jsonPath)) {
            return res.status(404).json({ message: 'Infoseclabs_Blogs.json not found' });
        }
        
        const rawData = fs.readFileSync(jsonPath, 'utf-8');
        const posts = JSON.parse(rawData);
        
        let imported = 0;
        let skipped = 0;
        
        for (const post of posts) {
            const title = post.post_title || 'Untitled';
            const slug = post.post_name || title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
            const content = post.post_content || '';
            const excerpt = post.post_excerpt || '';
            const status = post.post_status === 'publish' ? 'published' : 'draft';
            const created_at = post.post_date || new Date().toISOString();
            const category = post.categories && post.categories[0] ? post.categories[0].name : null;
            const featured_image = post.featured_image ? post.featured_image.url : null;
            
            // Check if post already exists
            const { rows: existing } = await db.query('SELECT id FROM blog_posts WHERE slug = ?', [slug]);
            
            if (existing.length > 0) {
                skipped++;
                continue;
            }
            
            // Insert post
            await db.query(
                `INSERT INTO blog_posts (title, slug, content, excerpt, featured_image, author_id, status, category, created_at) 
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                [title, slug, content, excerpt, featured_image, req.user.id, status, category, created_at]
            );
            imported++;
        }
        
        res.json({ 
            message: 'Import successful', 
            imported, 
            skipped, 
            total: posts.length 
        });
    } catch (error) {
        console.error('Import Error:', error);
        res.status(500).json({ message: 'Import failed: ' + error.message });
    }
};

// POST /api/blog/generate-title (Admin)
exports.generateTitle = async (req, res) => {
    try {
        const { content } = req.body;
        if (!content) return res.status(400).json({ message: 'Content required' });

        const settings = await getAiSettings();
        if (!settings.ai_api_key) return res.status(500).json({ message: 'AI API Key not configured' });

        const titles = await generateBlogTitle(content, settings.ai_api_key);
        res.json({ titles });
    } catch (error) {
        console.error('Title Gen Error:', error);
        res.status(500).json({ message: 'Failed to generate titles' });
    }
};

// POST /api/blog/enhance-content (Admin)
exports.enhanceContent = async (req, res) => {
    try {
        const { content } = req.body;
        if (!content) return res.status(400).json({ message: 'Content required' });

        const settings = await getAiSettings();
        if (!settings.ai_api_key) return res.status(500).json({ message: 'AI API Key not configured' });

        const enhancedContent = await enhanceBlogContent(content, settings.ai_api_key);
        res.json({ content: enhancedContent });
    } catch (error) {
        console.error('Enhance Content Error:', error);
        res.status(500).json({ message: 'Failed to enhance content' });
    }
};

// Helper to get AI settings
async function getAiSettings() {
    const result = await db.query("SELECT `key`, value FROM system_settings WHERE category = 'ai_integration'");
    let settings = {};
    result.rows.forEach(row => {
        try { settings[row.key] = JSON.parse(row.value); } 
        catch(e) { settings[row.key] = row.value; }
    });
    
    // Fallback key lookup
    if (Object.keys(settings).length === 0) {
         const keyResult = await db.query("SELECT value FROM system_settings WHERE `key` = 'ai_integration'");
         if (keyResult.rows.length > 0) {
             try { settings = JSON.parse(keyResult.rows[0].value); } catch(e) {}
         }
    }

    if (settings.ai_api_key && typeof settings.ai_api_key === 'string') {
        settings.ai_api_key = settings.ai_api_key.replace(/^"|"$/g, '');
    }
    return settings;
}

// POST /api/admin/blog (Admin) - Create post
exports.createPost = async (req, res) => {
    try {
        const { title, slug, content, excerpt, featured_image, featured_image_alt, status = 'draft', category, created_at, seo_title, seo_description, focus_keyword } = req.body;

        // Basic slug generation if not provided
        const finalSlug = slug || title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');

        // Use provided created_at or default to NOW()
        const postDate = created_at ? new Date(created_at) : new Date();

        await db.query(
            "INSERT INTO blog_posts (title, slug, content, excerpt, featured_image, featured_image_alt, author_id, status, category, created_at, seo_title, seo_description, focus_keyword) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            [title, finalSlug, content, excerpt, featured_image, featured_image_alt || null, req.user.id, status, category || null, postDate, seo_title || null, seo_description || null, focus_keyword || null]
        );

        res.status(201).json({ message: 'Post created' });
    } catch (error) {
        console.error('Create Post Error:', error);
        res.status(500).json({ message: 'Failed to create post' });
    }
};

// PUT /api/admin/blog/:id (Admin)
exports.updatePost = async (req, res) => {
    try {
        const { id } = req.params;
        const { title, slug, content, excerpt, featured_image, featured_image_alt, status, category, created_at, seo_title, seo_description, focus_keyword } = req.body;

        let query = "UPDATE blog_posts SET title=?, slug=?, content=?, excerpt=?, featured_image=?, featured_image_alt=?, status=?, category=?, seo_title=?, seo_description=?, focus_keyword=?, updated_at=NOW()";
        const params = [title, slug, content, excerpt, featured_image, featured_image_alt || null, status, category || null, seo_title || null, seo_description || null, focus_keyword || null];

        if (created_at) {
            query += ", created_at=?";
            params.push(new Date(created_at));
        }

        query += " WHERE id=?";
        params.push(id);

        await db.query(query, params);

        res.json({ message: 'Post updated' });
    } catch (error) {
        console.error('Update Post Error:', error);

        res.status(500).json({ message: 'Failed to update post' });
    }
};

// DELETE /api/admin/blog/:id (Admin)
exports.deletePost = async (req, res) => {
    try {
        const { id } = req.params;
        await db.query("DELETE FROM blog_posts WHERE id=?", [id]);
        res.json({ message: 'Post deleted' });
    } catch (error) {
        console.error('Delete Post Error:', error);
        res.status(500).json({ message: 'Failed to delete post' });
    }
};

// GET /api/admin/blog/:id (Admin) - Get single post for editing
exports.getPostById = async (req, res) => {
    try {
        const { id } = req.params;
        const { rows: posts } = await db.query("SELECT * FROM blog_posts WHERE id = ?", [id]);
        if (posts.length === 0) return res.status(404).json({ message: 'Post not found' });
        res.json(posts[0]);
    } catch (error) {
        console.error('Get Admin Post Error:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.getAllPostsAdmin = async (req, res) => {
    try {
        const { rows: posts } = await db.query("SELECT id, title, slug, status, created_at FROM blog_posts ORDER BY created_at DESC");
        res.json(posts);
    } catch (error) {
        console.error('Get All Admin Posts Error:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

// POST /api/admin/blog/upload (Admin)
exports.uploadImage = (req, res) => {
    if (!req.file) {
        return res.status(400).json({ message: 'No file uploaded' });
    }

    // Construct public URL
    // Assuming 'uploads' is served statically from root
    const fileUrl = `${process.env.CLIENT_ORIGIN || req.protocol + '://' + req.get('host')}/uploads/${req.file.filename}`;

    // Actually, CLIENT_ORIGIN is frontend. We need BACKEND URL.
    // If running separately, we typically use relative path or separate backend URL var.
    // Since images are served by express, we need backend domain.
    // However, frontend usually proxies /api, but /uploads might not be proxied if vite config only proxies /api.
    // Let's assume absolute URL for now, using the request host (backend).

    // Better: Return relative path "/uploads/filename" and let frontend handle or use backend base URL.
    // But for "Insert into content", an absolute URL is safer if the blog is displayed elsewhere.

    // Since vite proxy is often involved, "/uploads/..." works if vite proxies it.
    // Vite config usually matches "^/api". We might need to adjust vite config to proxy /uploads too.

    // Let's return the full backend URL for safety.
    const protocol = req.secure ? 'https' : 'http';
    const host = req.get('host'); // e.g. localhost:5001
    const fullUrl = `${protocol}://${host}/uploads/${req.file.filename}`;

    res.json({
        message: 'Image uploaded',
        url: fullUrl
    });
};

// GET /api/admin/blog/automation/status
exports.getAutomationStatus = async (req, res) => {
    try {
        const blogAutomationService = require('../services/blogAutomationService');
        const status = await blogAutomationService.getAutomationStatus();
        res.json(status);
    } catch (error) {
        console.error('Get Automation Status Error:', error);
        res.status(500).json({ message: 'Failed to get status' });
    }
};

// POST /api/admin/blog/automation/trigger
exports.triggerAutomation = async (req, res) => {
    try {
        const blogAutomationService = require('../services/blogAutomationService');
        // We don't await the whole process if it takes too long, 
        // OR we await it to give immediate feedback. 
        // Given React usage, awaiting (with loading spinner) is often better UX if < 60s.
        // Let's await it.
        const result = await blogAutomationService.generateAndPublish();
        
        if (result.success) {
            res.json({ message: 'Automation run successfully', details: result });
        } else {
            res.status(500).json({ message: 'Automation failed: ' + result.message });
        }
    } catch (error) {
        console.error('Trigger Automation Error:', error);
        res.status(500).json({ message: 'Failed to trigger automation' });
    }
};

// GET /api/admin/blog/automation/trending
exports.getTrendingTitles = async (req, res) => {
    try {
        const blogAutomationService = require('../services/blogAutomationService');
        const titles = await blogAutomationService.getTrendingCandidates();
        res.json(titles);
    } catch (error) {
        console.error('Error fetching trending titles:', error);
        res.status(500).json({ message: 'Failed to fetch titles' });
    }
};

// POST /api/admin/blog/automation/create-from-title
exports.createPostFromTitle = async (req, res) => {
    try {
        const blogAutomationService = require('../services/blogAutomationService');
        const newsItem = req.body; // Expects { title, source, contentSnippet, etc. }
        // Run asynchronously
        blogAutomationService.generateAndPublish(newsItem);
        res.json({ message: 'Automation triggered for selected title' });
    } catch (error) {
        res.status(500).json({ message: 'Failed to trigger automation' });
    }
};

// POST /api/admin/blog/automation/create-custom
exports.createPostCustom = async (req, res) => {
    try {
        const blogAutomationService = require('../services/blogAutomationService');
        const { topic, details } = req.body;
        if (!topic) return res.status(400).json({ message: 'Topic is required' });
        
        // Run asynchronously
        blogAutomationService.generateFromCustom(topic, details);
        res.json({ message: 'Automation triggered for custom topic' });
    } catch (error) {
        res.status(500).json({ message: 'Failed to trigger automation' });
    }
};
// GET /api/blog/categories (Admin) - Get all unique categories
exports.getCategories = async (req, res) => {
    try {
        const { rows } = await db.query(
            "SELECT DISTINCT category FROM blog_posts WHERE category IS NOT NULL AND category != '' ORDER BY category"
        );
        const categories = rows.map(r => r.category);
        res.json(categories);
    } catch (error) {
        console.error('Get Categories Error:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.getAutomationSettings = async (req, res) => {
    try {
        // Consolidate retrieval from 'blog_automation' category (primary)
        // while still supporting 'blog_integration' for backward compatibility during migration
        const result = await db.query(
            "SELECT `key`, value FROM system_settings WHERE category IN ('blog_integration', 'blog_automation')"
        );
        const settings = {};
        result.rows.forEach(row => {
            // If the same key exists in both, blog_automation (later in the list or alphabetical) will win
            // We'll prioritize values from blog_automation if they exist
            settings[row.key] = row.value;
        });
        res.json(settings);
    } catch (error) {
        console.error('getAutomationSettings Error:', error);
        res.status(500).json({ message: 'Server error' });
    }
};

exports.updateAutomationSettings = async (req, res) => {
    try {
        const { settings } = req.body;
        if (!settings || typeof settings !== 'object') {
            return res.status(400).json({ message: 'Invalid settings' });
        }

        for (const [key, value] of Object.entries(settings)) {
            // Standardize on 'blog_automation' category for all new updates
            await db.query(
                "INSERT INTO system_settings (`key`, value, category, updated_at) VALUES (?, ?, 'blog_automation', NOW()) ON DUPLICATE KEY UPDATE value = VALUES(value), category = VALUES(category), updated_at = NOW()",
                [key, String(value)]
            );
        }

        res.json({ success: true });
    } catch (error) {
        console.error('updateAutomationSettings Error:', error);
        res.status(500).json({ message: 'Server error' });
    }
};
