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 Batch aggregate.
 *
 * Exercises plan() with fuzzed drafts, then applies a random sequence of
 * state-mutating operations (startProduction, recordConsumption, complete, cancel).
 * 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=BatchFuzzTest
 */
class BatchFuzzTest {

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

        BatchNumber batchNumber;
        try {
            batchNumber = BatchNumber.generate(LocalDate.now(), 1);
        } catch (Exception e) {
            return;
        }

        switch (Batch.plan(draft, batchNumber)) {
            case Result.Failure(var err) -> { }
            case Result.Success(var batch) -> {
                int ops = data.consumeInt(1, 10);
                for (int i = 0; i < ops; i++) {
                    int op = data.consumeInt(0, 3);
                    switch (op) {
                        case 0 -> batch.startProduction();
                        case 1 -> {
                            batch.recordConsumption(new ConsumptionDraft(
                                    data.consumeString(50),
                                    data.consumeString(50),
                                    data.consumeString(30),
                                    data.consumeString(20)
                            ));
                        }
                        case 2 -> {
                            batch.complete(new CompleteBatchDraft(
                                    data.consumeString(30),
                                    data.consumeString(20),
                                    data.consumeString(30),
                                    data.consumeString(20),
                                    data.consumeString(100)
                            ));
                        }
                        case 3 -> batch.cancel(new CancelBatchDraft(data.consumeString(600)));
                    }
                }
            }
        }
    }

    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);
    }
}
