package de.effigenix.application.production;

import de.effigenix.application.production.command.ArchiveRecipeCommand;
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("ArchiveRecipe Use Case")
class ArchiveRecipeTest {

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

    private ArchiveRecipe archiveRecipe;
    private ActorId performedBy;

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

    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 draftRecipe() {
        return Recipe.create(new RecipeDraft(
                "Bratwurst", 1, RecipeType.FINISHED_PRODUCT,
                null, 85, 14, "100", "KILOGRAM", "article-123"
        )).unsafeGetValue();
    }

    @Test
    @DisplayName("should_ArchiveRecipe_When_RecipeIsActive")
    void should_ArchiveRecipe_When_RecipeIsActive() {
        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)));
        when(recipeRepository.save(any())).thenReturn(Result.success(null));

        var result = archiveRecipe.execute(new ArchiveRecipeCommand("recipe-1"), performedBy);

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

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

        var result = archiveRecipe.execute(new ArchiveRecipeCommand("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 = archiveRecipe.execute(new ArchiveRecipeCommand("nonexistent"), performedBy);

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

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

        var result = archiveRecipe.execute(new ArchiveRecipeCommand(recipe.id().value()), performedBy);

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

    @Test
    @DisplayName("should_FailWithInvalidStatusTransition_When_AlreadyArchived")
    void should_FailWithInvalidStatusTransition_When_AlreadyArchived() {
        var recipe = Recipe.reconstitute(
                RecipeId.of("recipe-2"), new RecipeName("Test"), 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)
        );
        when(authPort.can(performedBy, ProductionAction.RECIPE_WRITE)).thenReturn(true);
        when(recipeRepository.findById(RecipeId.of("recipe-2"))).thenReturn(Result.success(Optional.of(recipe)));

        var result = archiveRecipe.execute(new ArchiveRecipeCommand("recipe-2"), performedBy);

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