const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

async function main() {
    console.log('🌱 Planting realistic demo crop...');

    // 1. Ensure we have some Batches to link to
    const batchData = [
        { name: 'B-VEG-01', strain: 'Blue Dream', stage: 'VEGETATIVE', plantCount: 0 },
        { name: 'B-FLO-01', strain: 'Strawberry Cough', stage: 'FLOWERING', plantCount: 0 },
        { name: 'B-FLO-02', strain: 'OG Kush', stage: 'FLOWERING', plantCount: 0 },
        { name: 'B-DRY-01', strain: 'Sour Diesel', stage: 'DRYING', plantCount: 0 }
    ];

    const batches = [];
    for (const b of batchData) {
        let batch = await prisma.batch.findFirst({ where: { name: b.name } });
        if (!batch) {
            batch = await prisma.batch.create({
                data: {
                    name: b.name,
                    strain: b.strain,
                    stage: b.stage,
                    startDate: new Date(),
                    plantCount: 0
                }
            });
            console.log(`Created Batch: ${b.name}`);
        }
        batches.push(batch);
    }

    const [vegBatch, flowerBatch1, flowerBatch2, dryBatch] = batches;

    // 2. Get our Realistic Sections by Code
    // Veg Room Racks
    const vegSections = await prisma.facilitySection.findMany({
        where: { room: { code: 'VEG' } },
        include: { positions: true }
    });

    // Flower Room Benches
    const flowerSections = await prisma.facilitySection.findMany({
        where: { room: { code: 'FLO' } },
        include: { positions: true }
    });

    // Dry Room
    const drySections = await prisma.facilitySection.findMany({
        where: { room: { code: 'DRY' } },
        include: { positions: true }
    });

    console.log(`Found ${vegSections.length} Veg Sections, ${flowerSections.length} Flower Sections`);

    // 3. Helper to Fill Section
    async function fillSection(section, batch, fillPercentage = 0.8) {
        const positions = section.positions;
        const countToFill = Math.floor(positions.length * fillPercentage);

        console.log(`Filling ${section.name} with ${countToFill} plants (${batch.strain})...`);

        const positionsToFill = positions.slice(0, countToFill);

        let created = 0;
        // Chunk it to avoid massive transactions
        const chunkSize = 50;
        for (let i = 0; i < positionsToFill.length; i += chunkSize) {
            const chunk = positionsToFill.slice(i, i + chunkSize);

            await prisma.$transaction(async (tx) => {
                for (const pos of chunk) {
                    // Check if occupied
                    const existing = await tx.facilityPlant.findFirst({ where: { positionId: pos.id } });
                    if (!existing) {
                        await tx.facilityPlant.create({
                            data: {
                                tagNumber: `P-${Date.now()}-${Math.floor(Math.random() * 100000)}`,
                                batchId: batch.id,
                                positionId: pos.id,
                                address: `${section.code}-${pos.row}-${pos.column}`,
                                status: 'ACTIVE'
                            }
                        });
                        await tx.facilityPosition.update({
                            where: { id: pos.id },
                            data: { status: 'OCCUPIED' }
                        });
                        created++;
                    }
                }
            });
        }
        console.log(`  -> Planted ${created} plants.`);
    }

    // 4. Execute Fill
    for (const sec of vegSections) {
        await fillSection(sec, vegBatch, 0.9); // 90% full
    }

    // Split flower room between two strains
    for (let i = 0; i < flowerSections.length; i++) {
        const batch = i % 2 === 0 ? flowerBatch1 : flowerBatch2;
        await fillSection(flowerSections[i], batch, 0.95); // 95% full
    }

    for (const sec of drySections) {
        await fillSection(sec, dryBatch, 0.5); // 50% full
    }

    console.log('✅ Crop planted successfully!');
}

main()
    .catch((e) => {
        console.error(e);
        process.exit(1);
    })
    .finally(async () => {
        await prisma.$disconnect();
    });
