package de.effigenix.domain.production;

import com.code_intelligence.jazzer.api.FuzzedDataProvider;
import com.code_intelligence.jazzer.junit.FuzzTest;
import de.effigenix.shared.common.Result;

import java.time.LocalDate;

/**
 * Fuzz test for the ProductionOrder aggregate.
 *
 * Exercises create() with fuzzed drafts, then applies a random sequence of
 * state-mutating operations (release, startProduction, complete, cancel, reschedule).
 * Verifies that no input combination causes an unhandled exception –
 * all invalid inputs must be caught and returned as Result.Failure.
 *
 * Run: make fuzz  |  make fuzz/single TEST=ProductionOrderFuzzTest
 */
class ProductionOrderFuzzTest {

    @FuzzTest(maxDuration = "5m")
    void fuzzProductionOrder(FuzzedDataProvider data) {
        var draft = new ProductionOrderDraft(
                data.consumeString(50),
                data.consumeString(30),
                data.consumeString(20),
                consumeLocalDate(data),
                data.consumeString(10),
                data.consumeString(100)
        );

        switch (ProductionOrder.create(draft)) {
            case Result.Failure(var err) -> {
                // Invalid draft – expected
            }
            case Result.Success(var order) -> {
                int ops = data.consumeInt(1, 10);
                for (int i = 0; i < ops; i++) {
                    int op = data.consumeInt(0, 4);
                    switch (op) {
                        case 0 -> order.release();
                        case 1 -> order.startProduction(BatchId.of(data.consumeString(50)));
                        case 2 -> order.complete();
                        case 3 -> order.cancel(data.consumeString(50));
                        case 4 -> order.reschedule(consumeLocalDate(data));
                    }
                }
            }
        }
    }

    private static LocalDate consumeLocalDate(FuzzedDataProvider data) {
        if (data.consumeBoolean()) {
            return null;
        }
        int year = data.consumeInt(1900, 2100);
        int month = data.consumeInt(1, 12);
        int day = data.consumeInt(1, 28);
        return LocalDate.of(year, month, day);
    }
}
