package com.starry.admin.modules.order.listener;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;

import com.starry.admin.modules.order.module.dto.OrderRevocationContext;
import com.starry.admin.modules.order.module.entity.PlayOrderInfoEntity;
import com.starry.admin.modules.order.module.event.OrderRevocationEvent;
import com.starry.admin.modules.withdraw.service.IEarningsService;
import java.math.BigDecimal;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class OrderRevocationEarningsListenerTest {

    @Mock
    private IEarningsService earningsService;

    private OrderRevocationEarningsListener listener;

    @BeforeEach
    void setUp() {
        listener = new OrderRevocationEarningsListener(earningsService);
    }

    @Test
    void handle_deductCreatesCounterLineUsingOrderClerk() {
        OrderRevocationContext context = new OrderRevocationContext();
        context.setOrderId("order-reverse-2");
        context.setOperatorId("admin-reviewer");
        context.setDeductClerkEarnings(true);
        context.setEarningsAdjustAmount(BigDecimal.valueOf(25));

        PlayOrderInfoEntity order = new PlayOrderInfoEntity();
        order.setId("order-reverse-2");
        order.setTenantId("tenant-x");
        order.setAcceptBy("clerk-special");

        listener.handle(new OrderRevocationEvent(context, order));

        verify(earningsService)
                .createCounterLine("order-reverse-2", "tenant-x", "clerk-special", BigDecimal.valueOf(25), "admin-reviewer");
    }

    @Test
    void handle_deductFallsBackToEstimatedWhenAmountMissing() {
        OrderRevocationContext context = new OrderRevocationContext();
        context.setOrderId("order-reverse-3");
        context.setOperatorId("admin-reviewer");
        context.setDeductClerkEarnings(true);

        PlayOrderInfoEntity order = new PlayOrderInfoEntity();
        order.setId("order-reverse-3");
        order.setTenantId("tenant-y");
        order.setAcceptBy("clerk-owner");
        order.setEstimatedRevenue(BigDecimal.valueOf(52));

        listener.handle(new OrderRevocationEvent(context, order));

        verify(earningsService)
                .createCounterLine("order-reverse-3", "tenant-y", "clerk-owner", BigDecimal.valueOf(52), "admin-reviewer");
    }

    @Test
    void handle_disabledDeductIsNoOp() {
        OrderRevocationContext context = new OrderRevocationContext();
        context.setOrderId("order-none-3");
        context.setOperatorId("admin-noop");
        context.setDeductClerkEarnings(false);

        PlayOrderInfoEntity order = new PlayOrderInfoEntity();
        order.setId("order-none-3");

        listener.handle(new OrderRevocationEvent(context, order));

        verifyNoInteractions(earningsService);
    }
}
