package click.kamil.springstatemachineexporter.analysis.service;

import click.kamil.springstatemachineexporter.analysis.model.CallChain;
import click.kamil.springstatemachineexporter.analysis.model.LinkResolution;
import click.kamil.springstatemachineexporter.ast.common.CodebaseContext;
import click.kamil.springstatemachineexporter.model.Transition;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.nio.file.Path;

import static click.kamil.springstatemachineexporter.analysis.service.CentralDispatcherTestSupport.*;
import static org.assertj.core.api.Assertions.assertThat;

/**
 * Allocation-sensitive virtual {@code getType()} through a generic/interface carrier must
 * propagate {@code Enum.CONST.name()} instead of unioning every implementor.
 */
class AllocationSensitiveRichEventPipelineTest {

    private static final String MACHINE_CONFIG = "com.example.OrderStateMachineConfig";
    private static final String EVENT_TYPE = "com.example.OrderEvent";
    private static final String STATE_TYPE = "com.example.OrderState";

    @Test
    void linkerShouldResolvePayWhenConcreteRichEventFlowsThroughInterfaceParam(@TempDir Path tempDir)
            throws Exception {
        String source = """
            package com.example;
            public class ApiController {
                Dispatcher dispatcher;
                public void pay() { dispatcher.fire(new PayRichEvent()); }
            }
            class Dispatcher {
                StateMachine machine;
                void fire(RichEvent e) {
                    machine.sendEvent(OrderEvent.valueOf(e.getType()));
                }
            }
            interface RichEvent { String getType(); }
            class PayRichEvent implements RichEvent {
                public String getType() { return OrderEvent.PAY.name(); }
            }
            class ShipRichEvent implements RichEvent {
                public String getType() { return OrderEvent.SHIP.name(); }
            }
            class StateMachine { public void sendEvent(OrderEvent e) {} }
            enum OrderEvent { PAY, SHIP, CANCEL }
            enum OrderState { NEW, PAID, SHIPPED, CANCELLED }
            class OrderStateMachineConfig {}
            """;
        CodebaseContext context = scanSource(source, tempDir);

        Transition pay = transition("NEW", "PAID", EVENT_TYPE + ".PAY");
        Transition ship = transition("PAID", "SHIPPED", EVENT_TYPE + ".SHIP");
        Transition cancel = transition("NEW", "CANCELLED", EVENT_TYPE + ".CANCEL");

        CallChain linked = resolveLinkAndAssertSingleMatch(
                context,
                "com.example.ApiController",
                "pay",
                "com.example.StateMachine",
                "sendEvent",
                MACHINE_CONFIG,
                EVENT_TYPE,
                STATE_TYPE,
                EVENT_TYPE + ".PAY",
                EngineKind.JDT,
                pay,
                ship,
                cancel);

        assertThat(linked.getLinkResolution()).isEqualTo(LinkResolution.RESOLVED);
        assertThat(linked.getTriggerPoint().getPolymorphicEvents())
                .as("allocation-sensitive getType must not union ShipRichEvent")
                .filteredOn(pe -> pe != null && (pe.contains("PAY") || pe.contains("SHIP") || pe.contains("CANCEL")))
                .allMatch(pe -> pe.contains("PAY"));
    }

    @Test
    void linkerShouldStayFailClosedWhenRichEventFieldHasNoAllocation(@TempDir Path tempDir)
            throws Exception {
        String source = """
            package com.example;
            public class ApiController {
                Dispatcher dispatcher;
                public void dispatch() { dispatcher.fire(); }
            }
            class Dispatcher {
                StateMachine machine;
                RichEvent carrier;
                void fire() {
                    machine.sendEvent(OrderEvent.valueOf(carrier.getType()));
                }
            }
            interface RichEvent { String getType(); }
            class PayRichEvent implements RichEvent {
                public String getType() { return OrderEvent.PAY.name(); }
            }
            class ShipRichEvent implements RichEvent {
                public String getType() { return OrderEvent.SHIP.name(); }
            }
            class StateMachine { public void sendEvent(OrderEvent e) {} }
            enum OrderEvent { PAY, SHIP, CANCEL }
            enum OrderState { NEW, PAID, SHIPPED, CANCELLED }
            class OrderStateMachineConfig {}
            """;
        CodebaseContext context = scanSource(source, tempDir);

        Transition pay = transition("NEW", "PAID", EVENT_TYPE + ".PAY");
        Transition ship = transition("PAID", "SHIPPED", EVENT_TYPE + ".SHIP");

        CallChain raw = resolveChain(context, "com.example.ApiController", "dispatch",
                "com.example.StateMachine", "sendEvent", EngineKind.JDT);

        CallChain linked = linkChain(
                context,
                raw,
                MACHINE_CONFIG,
                EVENT_TYPE,
                STATE_TYPE,
                pay,
                ship);

        assertThat(linked.getMatchedTransitions()).isNullOrEmpty();
        assertThat(linked.getLinkResolution())
                .isIn(LinkResolution.AMBIGUOUS_WIDEN, LinkResolution.NO_MATCH, LinkResolution.UNRESOLVED_EXTERNAL);
    }
}
