import axios from 'axios';
import dotenv from 'dotenv';
import { blogPosts } from '../lib/blog-data';
import { pillarMeta } from '../lib/pillar-data';
import { authors } from '../lib/author-data';

dotenv.config();

const INDEXNOW_ENDPOINT = 'https://api.indexnow.org/indexnow';
const HOST = 'www.qrmaster.net';
// You need to generate a key from https://www.bing.com/indexnow and place it in your public folder
// Key must be set in .env as INDEXNOW_KEY
const KEY = process.env.INDEXNOW_KEY!;
const KEY_LOCATION = `https://${HOST}/${KEY}.txt`;

export async function submitToIndexNow(urls: string[]) {
    try {
        const payload = {
            host: HOST,
            key: KEY,
            keyLocation: KEY_LOCATION,
            urlList: urls,
        };

        console.log(`Submitting ${urls.length} URLs to IndexNow...`);
        const response = await axios.post(INDEXNOW_ENDPOINT, payload, {
            headers: {
                'Content-Type': 'application/json',
            },
        });

        if (response.status === 200 || response.status === 202) {
            console.log('✅ Successfully submitted URLs to IndexNow.');
        } else {
            console.error(`⚠️ IndexNow submission returned status: ${response.status}`);
        }
    } catch (error) {
        if (axios.isAxiosError(error)) {
            console.error('❌ Error submitting to IndexNow:', error.message);
            console.error('Response data:', error.response?.data);
        } else {
            console.error('❌ Unknown error submitting to IndexNow:', error);
        }
    }
}

// Function to gather all indexable URLs
export function getAllIndexableUrls(): string[] {
    const baseUrl = `https://${HOST}`;

    // Free tools
    const freeTools = [
        'barcode-generator', // Added as per request
        'url-qr-code', 'vcard-qr-code', 'text-qr-code', 'email-qr-code', 'sms-qr-code',
        'wifi-qr-code', 'crypto-qr-code', 'event-qr-code', 'facebook-qr-code',
        'instagram-qr-code', 'twitter-qr-code', 'youtube-qr-code', 'whatsapp-qr-code',
        'tiktok-qr-code', 'geolocation-qr-code', 'call-qr-code-generator', 'paypal-qr-code',
        'zoom-qr-code', 'teams-qr-code',
    ].map(slug => `${baseUrl}/tools/${slug}`);

    // Blog posts
    const blogPages = blogPosts.map(post => `${baseUrl}/blog/${post.slug}`);

    // Main pages (synced with sitemap.ts)
    const mainPages = [
        baseUrl,
        `${baseUrl}/about`,
        `${baseUrl}/contact`,
        `${baseUrl}/press`,
        `${baseUrl}/testimonials`,
        `${baseUrl}/qr-code-erstellen`,
        `${baseUrl}/qr-code-tracking`,
        `${baseUrl}/reprint-calculator`,
        `${baseUrl}/dynamic-qr-code-generator`,
        `${baseUrl}/bulk-qr-code-generator`,
        `${baseUrl}/custom-qr-code-generator`,
        `${baseUrl}/manage-qr-codes`,
        `${baseUrl}/pricing`,
        `${baseUrl}/tools`,
        `${baseUrl}/features`,
        `${baseUrl}/faq`,
        `${baseUrl}/blog`,
        `${baseUrl}/privacy`,
        `${baseUrl}/newsletter`,
    ];

    // Learn hub and pillar pages
    const learnPages = [
        `${baseUrl}/learn`,
        ...pillarMeta.map(pillar => `${baseUrl}/learn/${pillar.key}`)
    ];

    // Author pages
    const authorPages = authors.map(author => `${baseUrl}/authors/${author.slug}`);

    return [...mainPages, ...freeTools, ...blogPages, ...learnPages, ...authorPages];
}

// If run directly
if (require.main === module) {
    const urls = getAllIndexableUrls();
    submitToIndexNow(urls);
}
