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

async function main() {
    console.log('🌱 Seeding METRC demo data...');

    // 1. Get existing Batches
    const batches = await prisma.batch.findMany({
        take: 5
    });

    if (batches.length === 0) {
        console.error('No Batches found. Please run main seed first.');
        return;
    }

    // 2. Get existing FacilityPositions for Floor 1
    const floor = await prisma.facilityFloor.findFirst({
        where: { number: 1 },
        include: { rooms: { include: { sections: { include: { positions: true } } } } }
    });

    if (!floor) {
        console.error('Floor 1 not found');
        return;
    }

    // Flatten positions
    const positions = [];
    for (const room of floor.rooms) {
        for (const section of room.sections) {
            for (const pos of section.positions) {
                // Add room/section info manually since we flattened
                pos.section = { room: room, code: section.code };
                positions.push(pos);
            }
        }
    }

    // Take 50
    const targetPositions = positions.slice(0, 50);

    if (targetPositions.length === 0) {
        console.error('No FacilityPositions found on Floor 1.');
        return;
    }

    console.log(`Found ${batches.length} batches and ${targetPositions.length} positions on Floor 1.`);

    // 3. Clear existing demo plants
    const deleted = await prisma.facilityPlant.deleteMany({
        where: {
            tagNumber: { startsWith: '1A40603000' }
        }
    });

    // Also reset position status for those cleaned up? 
    // Too complex, just overwrite status for new ones.

    console.log(`Cleared ${deleted.count} existing demo plants.`);

    // 4. Create Plants
    let createdCount = 0;

    for (const [index, pos] of targetPositions.entries()) {
        const batch = batches[index % batches.length];

        // METRC Tag format: 1A40603000 + 7 digits
        const tagSuffix = (1000000 + index).toString();
        const tag = `1A40603000${tagSuffix}`;

        try {
            // Delete any existing plant in this position to avoid collision if not caught by tag delete
            await prisma.facilityPlant.deleteMany({ where: { positionId: pos.id } });

            const plant = await prisma.facilityPlant.create({
                data: {
                    tagNumber: tag,
                    // valid fields from schema:
                    batchId: batch.id,
                    positionId: pos.id,
                    address: `${pos.section.room.code}-${pos.section.code}-R${pos.row}C${pos.column}`,
                    status: 'ACTIVE'
                }
            });

            // UPDATE POSITION STATUS
            await prisma.facilityPosition.update({
                where: { id: pos.id },
                data: { status: 'OCCUPIED' }
            });

            // 5. Create Location History (Audit)
            await prisma.plantLocationHistory.create({
                data: {
                    plantId: plant.id,
                    fromAddress: null,
                    toAddress: plant.address,
                    movedAt: new Date(),
                    reason: 'Initial planting',
                    movedById: 'system'
                }
            });

            // Maybe a move for some plants
            if (index % 3 === 0) {
                const oldAddress = `NUR-1-R1C1`;
                await prisma.plantLocationHistory.create({
                    data: {
                        plantId: plant.id,
                        fromAddress: oldAddress,
                        toAddress: plant.address,
                        movedAt: new Date(Date.now() - Math.random() * 5 * 24 * 60 * 60 * 1000),
                        reason: 'Moved to flower',
                        movedById: 'system'
                    }
                });
            }

            createdCount++;
        } catch (error) {
            // Ignore unique constraint errors if position already taken (though we cleared matches)
            if (!error.message.includes('Unique constraint')) {
                console.error(`Failed to create plant ${tag}:`, error.message);
            }
        }
    }

    console.log(`✨ Successfully created ${createdCount} METRC demo plants linked to batches.`);
}

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