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;

/**
 * Machine enums with ctor args ({@code PAY("pay", true)}) must still allocation-resolve
 * when {@code getType()} returns the enum constant or {@code .name()}.
 */
class AllocationSensitiveEnumCtorPipelineTest {

    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";

    private static final String ENUM_WITH_CTOR = """
            enum OrderEvent {
                PAY("pay", true), SHIP("ship", true), LOG("log", false), CANCEL("cancel", true);
                private final String code;
                private final boolean event;
                OrderEvent(String code, boolean event) { this.code = code; this.event = event; }
                public String getCode() { return code; }
                public boolean isEvent() { return event; }
            }
            enum OrderState { NEW, PAID, SHIPPED, CANCELLED }
            class StateMachine { public void sendEvent(OrderEvent e) {} }
            class OrderStateMachineConfig {}
            """;

    @Test
    void namePeelWithEnumCtorArgs(@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(); }
            }
            """ + ENUM_WITH_CTOR;
        assertResolvedPay(source, tempDir);
    }

    @Test
    void enumConstReturnWithCtorArgs(@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(e.getType());
                }
            }
            interface RichEvent { OrderEvent getType(); }
            class PayRichEvent implements RichEvent {
                public OrderEvent getType() { return OrderEvent.PAY; }
            }
            class ShipRichEvent implements RichEvent {
                public OrderEvent getType() { return OrderEvent.SHIP; }
            }
            """ + ENUM_WITH_CTOR;
        assertResolvedPay(source, tempDir);
    }

    @Test
    void getCodeFromEnumCtorFieldStaysFailClosed(@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.getCode(); }
            }
            class ShipRichEvent implements RichEvent {
                public String getType() { return OrderEvent.SHIP.getCode(); }
            }
            """ + ENUM_WITH_CTOR;
        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", "pay",
                "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);
    }

    private static void assertResolvedPay(String source, Path tempDir) throws Exception {
        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);
    }
}
