package de.effigenix.application.production;

import de.effigenix.application.production.command.ActivateRecipeCommand;
import de.effigenix.domain.production.*;
import de.effigenix.shared.common.Quantity;
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.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("ActivateRecipe Use Case")
class ActivateRecipeTest {

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

    private ActivateRecipe activateRecipe;
    private ActorId performedBy;

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

    private Recipe draftRecipeWithIngredient() {
        var recipe = Recipe.create(new RecipeDraft(
                "Bratwurst", 1, RecipeType.FINISHED_PRODUCT,
                null, 85, 14, "100", "KILOGRAM", "article-123"
        )).unsafeGetValue();
        recipe.addIngredient(new IngredientDraft(1, "article-123", "5.5", "KILOGRAM", null, false));
        return recipe;
    }

    private Recipe draftRecipeWithoutIngredient() {
        return Recipe.create(new RecipeDraft(
                "Bratwurst", 1, RecipeType.FINISHED_PRODUCT,
                null, 85, 14, "100", "KILOGRAM", "article-123"
        )).unsafeGetValue();
    }

    private Recipe activeRecipe() {
        return Recipe.reconstitute(
                RecipeId.of("recipe-1"), new RecipeName("Test"), 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)
        );
    }

    @Test
    @DisplayName("should_ActivateRecipe_When_DraftWithIngredients")
    void should_ActivateRecipe_When_DraftWithIngredients() {
        var recipe = draftRecipeWithIngredient();
        when(authPort.can(performedBy, ProductionAction.RECIPE_WRITE)).thenReturn(true);
        when(recipeRepository.findById(recipe.id())).thenReturn(Result.success(Optional.of(recipe)));
        when(recipeRepository.save(any())).thenReturn(Result.success(null));

        var result = activateRecipe.execute(new ActivateRecipeCommand(recipe.id().value()), performedBy);

        assertThat(result.isSuccess()).isTrue();
        assertThat(result.unsafeGetValue().status()).isEqualTo(RecipeStatus.ACTIVE);
        verify(recipeRepository).save(argThat(r -> r.status() == RecipeStatus.ACTIVE));
    }

    @Test
    @DisplayName("should_FailWithUnauthorized_When_ActorLacksPermission")
    void should_FailWithUnauthorized_When_ActorLacksPermission() {
        when(authPort.can(performedBy, ProductionAction.RECIPE_WRITE)).thenReturn(false);

        var result = activateRecipe.execute(new ActivateRecipeCommand("recipe-1"), performedBy);

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

    @Test
    @DisplayName("should_FailWithRecipeNotFound_When_RecipeDoesNotExist")
    void should_FailWithRecipeNotFound_When_RecipeDoesNotExist() {
        when(authPort.can(performedBy, ProductionAction.RECIPE_WRITE)).thenReturn(true);
        when(recipeRepository.findById(RecipeId.of("nonexistent"))).thenReturn(Result.success(Optional.empty()));

        var result = activateRecipe.execute(new ActivateRecipeCommand("nonexistent"), performedBy);

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

    @Test
    @DisplayName("should_FailWithNoIngredients_When_DraftHasNoIngredients")
    void should_FailWithNoIngredients_When_DraftHasNoIngredients() {
        var recipe = draftRecipeWithoutIngredient();
        when(authPort.can(performedBy, ProductionAction.RECIPE_WRITE)).thenReturn(true);
        when(recipeRepository.findById(recipe.id())).thenReturn(Result.success(Optional.of(recipe)));

        var result = activateRecipe.execute(new ActivateRecipeCommand(recipe.id().value()), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(RecipeError.NoIngredients.class);
        verify(recipeRepository, never()).save(any());
    }

    @Test
    @DisplayName("should_FailWithInvalidStatusTransition_When_AlreadyActive")
    void should_FailWithInvalidStatusTransition_When_AlreadyActive() {
        var recipe = activeRecipe();
        when(authPort.can(performedBy, ProductionAction.RECIPE_WRITE)).thenReturn(true);
        when(recipeRepository.findById(RecipeId.of("recipe-1"))).thenReturn(Result.success(Optional.of(recipe)));

        var result = activateRecipe.execute(new ActivateRecipeCommand("recipe-1"), performedBy);

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