package de.effigenix.application.production;

import de.effigenix.application.production.command.ReleaseProductionOrderCommand;
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.security.ActorId;
import de.effigenix.shared.security.AuthorizationPort;
import de.effigenix.shared.persistence.UnitOfWork;
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.List;
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("ReleaseProductionOrder Use Case")
class ReleaseProductionOrderTest {

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

    private ReleaseProductionOrder releaseProductionOrder;
    private ActorId performedBy;

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

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

    private ReleaseProductionOrderCommand validCommand() {
        return new ReleaseProductionOrderCommand("order-1");
    }

    private ProductionOrder plannedOrder() {
        return ProductionOrder.reconstitute(
                ProductionOrderId.of("order-1"),
                RecipeId.of("recipe-1"),
                ProductionOrderStatus.PLANNED,
                null,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                PLANNED_DATE,
                Priority.NORMAL,
                null,
                null,
                OffsetDateTime.now(ZoneOffset.UTC),
                OffsetDateTime.now(ZoneOffset.UTC),
                1L
        );
    }

    private ProductionOrder releasedOrder() {
        return ProductionOrder.reconstitute(
                ProductionOrderId.of("order-1"),
                RecipeId.of("recipe-1"),
                ProductionOrderStatus.RELEASED,
                null,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                PLANNED_DATE,
                Priority.NORMAL,
                null,
                null,
                OffsetDateTime.now(ZoneOffset.UTC),
                OffsetDateTime.now(ZoneOffset.UTC),
                1L
        );
    }

    private Recipe activeRecipe() {
        return Recipe.reconstitute(
                RecipeId.of("recipe-1"), new RecipeName("Bratwurst"), 1, RecipeType.FINISHED_PRODUCT,
                null, new YieldPercentage(85), 14,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                "article-123", RecipeStatus.ACTIVE, List.of(), List.of(),
                OffsetDateTime.now(ZoneOffset.UTC), OffsetDateTime.now(ZoneOffset.UTC)
        );
    }

    private Recipe archivedRecipe() {
        return Recipe.reconstitute(
                RecipeId.of("recipe-1"), new RecipeName("Bratwurst"), 1, RecipeType.FINISHED_PRODUCT,
                null, new YieldPercentage(85), 14,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                "article-123", RecipeStatus.ARCHIVED, List.of(), List.of(),
                OffsetDateTime.now(ZoneOffset.UTC), OffsetDateTime.now(ZoneOffset.UTC)
        );
    }

    @Test
    @DisplayName("should release PLANNED order when recipe is ACTIVE")
    void should_Release_When_ValidCommand() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(plannedOrder())));
        when(recipeRepository.findById(RecipeId.of("recipe-1")))
                .thenReturn(Result.success(Optional.of(activeRecipe())));
        when(productionOrderRepository.save(any())).thenReturn(Result.success(null));

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

        assertThat(result.isSuccess()).isTrue();
        assertThat(result.unsafeGetValue().status()).isEqualTo(ProductionOrderStatus.RELEASED);
        verify(productionOrderRepository).save(any(ProductionOrder.class));
    }

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

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

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

    @Test
    @DisplayName("should fail when production 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 = releaseProductionOrder.execute(validCommand(), performedBy);

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

    @Test
    @DisplayName("should fail when recipe is not ACTIVE (ARCHIVED)")
    void should_Fail_When_RecipeNotActive() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(plannedOrder())));
        when(recipeRepository.findById(RecipeId.of("recipe-1")))
                .thenReturn(Result.success(Optional.of(archivedRecipe())));

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

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

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

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

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

    @Test
    @DisplayName("should fail when order is already RELEASED (invalid status transition)")
    void should_Fail_When_AlreadyReleased() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(releasedOrder())));
        when(recipeRepository.findById(RecipeId.of("recipe-1")))
                .thenReturn(Result.success(Optional.of(activeRecipe())));

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

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.InvalidStatusTransition.class);
        var err = (ProductionOrderError.InvalidStatusTransition) result.unsafeGetError();
        assertThat(err.current()).isEqualTo(ProductionOrderStatus.RELEASED);
        assertThat(err.target()).isEqualTo(ProductionOrderStatus.RELEASED);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when order repository findById returns error")
    void should_Fail_When_OrderRepositoryError() {
        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 = releaseProductionOrder.execute(validCommand(), performedBy);

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

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

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

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

    @Test
    @DisplayName("should fail when save fails")
    void should_Fail_When_SaveFails() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(plannedOrder())));
        when(recipeRepository.findById(RecipeId.of("recipe-1")))
                .thenReturn(Result.success(Optional.of(activeRecipe())));
        when(productionOrderRepository.save(any()))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("disk full")));

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

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