package de.effigenix.application.production;

import de.effigenix.application.production.command.CancelProductionOrderCommand;
import de.effigenix.domain.production.*;
import de.effigenix.shared.common.Quantity;
import de.effigenix.shared.common.RepositoryError;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.common.UnitOfMeasure;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;
import de.effigenix.shared.security.AuthorizationPort;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Optional;
import java.util.function.Supplier;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
@DisplayName("CancelProductionOrder Use Case")
class CancelProductionOrderTest {

    @Mock private ProductionOrderRepository productionOrderRepository;
    @Mock private AuthorizationPort authPort;
    @Mock private UnitOfWork unitOfWork;

    private CancelProductionOrder cancelProductionOrder;
    private ActorId performedBy;

    private static final LocalDate PLANNED_DATE = LocalDate.now().plusDays(7);

    @BeforeEach
    void setUp() {
        cancelProductionOrder = new CancelProductionOrder(productionOrderRepository, authPort, unitOfWork);
        performedBy = ActorId.of("admin-user");
        lenient().when(unitOfWork.executeAtomically(any())).thenAnswer(inv -> ((Supplier<?>) inv.getArgument(0)).get());
    }

    private CancelProductionOrderCommand validCommand() {
        return new CancelProductionOrderCommand("order-1", "Kunde hat storniert");
    }

    private ProductionOrder orderWithStatus(ProductionOrderStatus status) {
        return ProductionOrder.reconstitute(
                ProductionOrderId.of("order-1"),
                RecipeId.of("recipe-1"),
                status,
                status == ProductionOrderStatus.IN_PROGRESS ? BatchId.of("batch-1") : null,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                PLANNED_DATE,
                Priority.NORMAL,
                null,
                null,
                OffsetDateTime.now(ZoneOffset.UTC),
                OffsetDateTime.now(ZoneOffset.UTC),
                1L
        );
    }

    @Test
    @DisplayName("should cancel PLANNED order")
    void should_Cancel_PlannedOrder() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(orderWithStatus(ProductionOrderStatus.PLANNED))));
        when(productionOrderRepository.save(any())).thenReturn(Result.success(null));

        var result = cancelProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isSuccess()).isTrue();
        assertThat(result.unsafeGetValue().status()).isEqualTo(ProductionOrderStatus.CANCELLED);
        assertThat(result.unsafeGetValue().cancelledReason()).isEqualTo("Kunde hat storniert");
        verify(productionOrderRepository).save(any(ProductionOrder.class));
    }

    @Test
    @DisplayName("should cancel RELEASED order")
    void should_Cancel_ReleasedOrder() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(orderWithStatus(ProductionOrderStatus.RELEASED))));
        when(productionOrderRepository.save(any())).thenReturn(Result.success(null));

        var result = cancelProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isSuccess()).isTrue();
        assertThat(result.unsafeGetValue().status()).isEqualTo(ProductionOrderStatus.CANCELLED);
        assertThat(result.unsafeGetValue().cancelledReason()).isEqualTo("Kunde hat storniert");
        verify(productionOrderRepository).save(any(ProductionOrder.class));
    }

    @Test
    @DisplayName("should fail when order is IN_PROGRESS")
    void should_Fail_When_InProgress() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(orderWithStatus(ProductionOrderStatus.IN_PROGRESS))));

        var result = cancelProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.InvalidStatusTransition.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when order is COMPLETED")
    void should_Fail_When_Completed() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(orderWithStatus(ProductionOrderStatus.COMPLETED))));

        var result = cancelProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.InvalidStatusTransition.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when order is already CANCELLED")
    void should_Fail_When_AlreadyCancelled() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(orderWithStatus(ProductionOrderStatus.CANCELLED))));

        var result = cancelProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.InvalidStatusTransition.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when order not found")
    void should_Fail_When_OrderNotFound() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.empty()));

        var result = cancelProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.ProductionOrderNotFound.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when unauthorized")
    void should_Fail_When_Unauthorized() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(false);

        var result = cancelProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.Unauthorized.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when repository returns error")
    void should_Fail_When_RepositoryError() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("connection lost")));

        var result = cancelProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.RepositoryFailure.class);
    }
}
