/**
 * Migration: Seed team, contact, and other missing pages as Lexical block content into Payload CMS.
 *
 * Usage:
 *   pnpm tsx scripts/seed-pages.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 = [
    // ─── Team (DE) ────────────────────────────────────────────
    {
        title: 'Team',
        slug: 'team',
        locale: 'de',
        layout: 'fullBleed',
        excerpt: '',
        _status: 'published',
        content: lexicalDoc([
            lexicalBlock('heroSection', {
                badge: 'Das Team',
                title: 'Tradition trifft Moderne',
                subtitle: 'Zwei Generationen, eine Vision: Deutschlands zuverlässigster Partner für Kabel & Leitungen.',
                alignment: 'center',
            }),
            lexicalBlock('teamProfile', {
                name: 'Michael Bodemer',
                role: 'Geschäftsführer',
                quote: 'Innovation entsteht dort, wo Erfahrung auf frische Ideen trifft.',
                description: 'Als Geschäftsführer verbindet Michael jahrzehntelange Branchenexpertise mit einem klaren Blick für die Zukunft. Sein Fokus liegt auf nachhaltigen Lösungen und modernster Technologie.',
                linkedinUrl: 'https://www.linkedin.com/in/michael-bodemer-33b493122/',
                layout: 'imageRight',
                colorScheme: 'dark',
            }),
            lexicalBlock('stats', {
                stats: [
                    { value: '30+', label: 'Jahre Expertise' },
                    { value: 'Global', label: 'Netzwerk' },
                ],
            }),
            lexicalBlock('teamProfile', {
                name: 'Klaus Mintel',
                role: 'Gründer & Berater',
                quote: 'Qualität ist kein Zufall – sie ist das Ergebnis von Engagement und Erfahrung.',
                description: 'Klaus gründete KLZ Cables und hat das Unternehmen zu einem der zuverlässigsten Partner der Kabelindustrie aufgebaut. Er bringt Jahrzehnte an Expertise ein.',
                linkedinUrl: 'https://www.linkedin.com/in/klaus-mintel-b80a8b193/',
                layout: 'imageLeft',
                colorScheme: 'light',
            }),
            lexicalBlock('manifestoGrid', {
                title: 'Unsere Werte',
                subtitle: 'Was uns antreibt',
                tagline: 'Seit der Gründung leiten uns klare Prinzipien, die wir jeden Tag leben.',
                items: [
                    { title: 'Qualität', description: 'Wir liefern nur Produkte, die höchsten Standards entsprechen.' },
                    { title: 'Zuverlässigkeit', description: 'Termingerechte Lieferung ist für uns selbstverständlich.' },
                    { title: 'Partnerschaft', description: 'Langfristige Beziehungen sind die Grundlage unseres Erfolgs.' },
                    { title: 'Innovation', description: 'Wir investieren in neue Technologien und nachhaltige Lösungen.' },
                    { title: 'Transparenz', description: 'Offene Kommunikation und faire Preise zeichnen uns aus.' },
                    { title: 'Nachhaltigkeit', description: 'Verantwortung für Umwelt und Gesellschaft ist Teil unserer DNA.' },
                ],
            }),
            // Removed the imageGallery since it requires at least 1 image and we don't have media upload IDs yet.
        ]),
    },
    // ─── Team (EN) ────────────────────────────────────────────
    {
        title: 'Team',
        slug: 'team',
        locale: 'en',
        layout: 'fullBleed',
        excerpt: '',
        _status: 'published',
        content: lexicalDoc([
            lexicalBlock('heroSection', {
                badge: 'The Team',
                title: 'Tradition Meets Innovation',
                subtitle: 'Two generations, one vision: Germany\'s most reliable partner for cables & wiring.',
                alignment: 'center',
            }),
            lexicalBlock('teamProfile', {
                name: 'Michael Bodemer',
                role: 'Managing Director',
                quote: 'Innovation happens where experience meets fresh ideas.',
                description: 'As Managing Director, Michael combines decades of industry expertise with a clear vision for the future. His focus is on sustainable solutions and cutting-edge technology.',
                linkedinUrl: 'https://www.linkedin.com/in/michael-bodemer-33b493122/',
                layout: 'imageRight',
                colorScheme: 'dark',
            }),
            lexicalBlock('stats', {
                stats: [
                    { value: '30+', label: 'Years of Expertise' },
                    { value: 'Global', label: 'Network' },
                ],
            }),
            lexicalBlock('teamProfile', {
                name: 'Klaus Mintel',
                role: 'Founder & Advisor',
                quote: 'Quality is no accident – it is the result of commitment and experience.',
                description: 'Klaus founded KLZ Cables and built the company into one of the most reliable partners in the cable industry. He brings decades of expertise.',
                linkedinUrl: 'https://www.linkedin.com/in/klaus-mintel-b80a8b193/',
                layout: 'imageLeft',
                colorScheme: 'light',
            }),
            lexicalBlock('manifestoGrid', {
                title: 'Our Values',
                subtitle: 'What drives us',
                tagline: 'Since our founding, clear principles have guided us every day.',
                items: [
                    { title: 'Quality', description: 'We only deliver products that meet the highest standards.' },
                    { title: 'Reliability', description: 'On-time delivery is our standard.' },
                    { title: 'Partnership', description: 'Long-term relationships are the foundation of our success.' },
                    { title: 'Innovation', description: 'We invest in new technologies and sustainable solutions.' },
                    { title: 'Transparency', description: 'Open communication and fair pricing define us.' },
                    { title: 'Sustainability', description: 'Responsibility for the environment and society is part of our DNA.' },
                ],
            }),
        ]),
    },
    // ─── Contact (DE) ─────────────────────────────────────────
    {
        title: 'Kontakt',
        slug: 'kontakt',
        locale: 'de',
        layout: 'fullBleed',
        excerpt: '',
        _status: 'published',
        content: lexicalDoc([
            lexicalBlock('heroSection', {
                badge: 'Kontakt',
                title: 'Sprechen Sie mit uns',
                subtitle: 'Wir sind für Sie da. Kontaktieren Sie uns für Beratung, Angebote oder technische Fragen.',
                alignment: 'left',
            }),
            lexicalBlock('contactSection', {
                showForm: true,
                showMap: true,
                showHours: true,
            }),
        ]),
    },
    // ─── Contact (EN) ─────────────────────────────────────────
    {
        title: 'Contact',
        slug: 'contact',
        locale: 'en',
        layout: 'fullBleed',
        excerpt: '',
        _status: 'published',
        content: lexicalDoc([
            lexicalBlock('heroSection', {
                badge: 'Contact',
                title: 'Talk to us',
                subtitle: 'We are here for you. Contact us for consulting, quotes, or technical questions.',
                alignment: 'left',
            }),
            lexicalBlock('contactSection', {
                showForm: true,
                showMap: true,
                showHours: true,
            }),
        ]),
    },
];

async function seedPages() {
    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,
                locale: page.locale,
                data: {
                    title: page.title,
                    layout: page.layout as any,
                    _status: page._status as any,
                    content: page.content as any,
                },
            });
            console.log(`✅ Updated: ${page.slug} (${page.locale})`);
        } else {
            await payload.create({
                collection: 'pages',
                locale: page.locale,
                data: {
                    title: page.title,
                    slug: page.slug,
                    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🎉 All pages seeded successfully!');
    process.exit(0);
}

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