/**
 * Migration: Seed homepage ('start') as Lexical block content into Payload CMS.
 *
 * Usage:
 *   pnpm tsx scripts/seed-home.ts
 */
import { getPayload } from 'payload';
import configPromise from '@payload-config';

function lexicalBlock(blockType: string, fields: Record<string, any> = {}) {
    return {
        type: 'block',
        version: 2,
        fields: {
            blockType,
            ...fields,
        },
    };
}

function lexicalDoc(blocks: any[]) {
    return {
        root: {
            type: 'root',
            format: '',
            indent: 0,
            version: 1,
            children: blocks,
            direction: 'ltr',
        },
    };
}

const PAGES = [
    // ─── Homepage (DE) ─────────────────────────────────────────
    {
        title: 'Startseite',
        slug: 'start',
        locale: 'de',
        layout: 'fullBleed',
        excerpt: 'Ihr Experte für hochwertige Stromkabel, Mittelspannungslösungen und Solarkabel. Zuverlässige Infrastruktur für eine grüne Energiezukunft.',
        _status: 'published',
        content: lexicalDoc([
            lexicalBlock('homeHero', { note: 'Hero section with primary video and CTA.' }),
            lexicalBlock('homeProductCategories', { note: 'Product categories overview based on CMS data.' }),
            lexicalBlock('homeWhatWeDo', { note: 'What we do / capabilities overview.' }),
            lexicalBlock('homeRecentPosts', { note: 'Latest 3 blog articles snippet.' }),
            lexicalBlock('homeExperience', { note: 'Experience and history timeline snippet.' }),
            lexicalBlock('homeWhyChooseUs', { note: 'Why choose KLZ Cables metrics and selling points.' }),
            lexicalBlock('homeMeetTheTeam', { note: 'High-level Meet the Team teaser.' }),
            lexicalBlock('homeGallery', { note: 'Image gallery from our facilities.' }),
            lexicalBlock('homeVideo', { note: 'Secondary informative background video.' }),
            lexicalBlock('homeCTA', { note: 'Bottom call to action linking to contact.' }),
        ]),
    },
    // ─── Homepage (EN) ─────────────────────────────────────────
    {
        title: 'Homepage',
        slug: 'start',
        locale: 'en',
        layout: 'fullBleed',
        excerpt: 'Your expert for high-quality power cables, medium voltage solutions, and solar cables. Reliable infrastructure for a green energy future.',
        _status: 'published',
        content: lexicalDoc([
            lexicalBlock('homeHero', { note: 'Hero section with primary video and CTA.' }),
            lexicalBlock('homeProductCategories', { note: 'Product categories overview based on CMS data.' }),
            lexicalBlock('homeWhatWeDo', { note: 'What we do / capabilities overview.' }),
            lexicalBlock('homeRecentPosts', { note: 'Latest 3 blog articles snippet.' }),
            lexicalBlock('homeExperience', { note: 'Experience and history timeline snippet.' }),
            lexicalBlock('homeWhyChooseUs', { note: 'Why choose KLZ Cables metrics and selling points.' }),
            lexicalBlock('homeMeetTheTeam', { note: 'High-level Meet the Team teaser.' }),
            lexicalBlock('homeGallery', { note: 'Image gallery from our facilities.' }),
            lexicalBlock('homeVideo', { note: 'Secondary informative background video.' }),
            lexicalBlock('homeCTA', { note: 'Bottom call to action linking to contact.' }),
        ]),
    },
];

async function seedHome() {
    const payload = await getPayload({ config: configPromise });

    for (const page of PAGES) {
        const existing = await payload.find({
            collection: 'pages',
            where: {
                slug: { equals: page.slug },
                locale: { equals: page.locale },
            },
            limit: 1,
        });

        const docs = existing.docs as any[];

        if (docs.length > 0) {
            await payload.update({
                collection: 'pages',
                id: docs[0].id,
                data: {
                    title: page.title,
                    layout: page.layout as any,
                    excerpt: page.excerpt,
                    _status: page._status as any,
                    content: page.content as any,
                },
            });
            console.log(`✅ Updated: ${page.slug} (${page.locale})`);
        } else {
            await payload.create({
                collection: 'pages',
                data: {
                    title: page.title,
                    slug: page.slug,
                    locale: page.locale,
                    layout: page.layout as any,
                    excerpt: page.excerpt,
                    _status: page._status as any,
                    content: page.content as any,
                },
            });
            console.log(`✅ Created: ${page.slug} (${page.locale})`);
        }
    }

    console.log('\n🎉 Homepage seeded successfully!');
    process.exit(0);
}

seedHome().catch((err) => {
    console.error('❌ Seed failed:', err);
    process.exit(1);
});
