package de.effigenix.application.production;

import de.effigenix.application.production.command.PlanBatchCommand;
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("PlanBatch Use Case")
class PlanBatchTest {

    @Mock private BatchRepository batchRepository;
    @Mock private RecipeRepository recipeRepository;
    @Mock private BatchNumberGenerator batchNumberGenerator;
    @Mock private AuthorizationPort authPort;
    @Mock private UnitOfWork unitOfWork;

    private PlanBatch planBatch;
    private ActorId performedBy;

    private static final LocalDate PRODUCTION_DATE = LocalDate.of(2026, 3, 1);
    private static final LocalDate BEST_BEFORE_DATE = LocalDate.of(2026, 6, 1);
    private static final BatchNumber BATCH_NUMBER = BatchNumber.generate(PRODUCTION_DATE, 1);

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

    private PlanBatchCommand validCommand() {
        return new PlanBatchCommand("recipe-1", "100", "KILOGRAM", PRODUCTION_DATE, BEST_BEFORE_DATE);
    }

    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.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.DRAFT, List.of(), List.of(),
                OffsetDateTime.now(ZoneOffset.UTC), OffsetDateTime.now(ZoneOffset.UTC)
        );
    }

    @Test
    @DisplayName("should plan batch when recipe is ACTIVE and all data valid")
    void should_PlanBatch_When_ValidCommand() {
        when(authPort.can(performedBy, ProductionAction.BATCH_WRITE)).thenReturn(true);
        when(recipeRepository.findById(RecipeId.of("recipe-1")))
                .thenReturn(Result.success(Optional.of(activeRecipe())));
        when(batchNumberGenerator.generateNext(PRODUCTION_DATE))
                .thenReturn(Result.success(BATCH_NUMBER));
        when(batchRepository.save(any())).thenReturn(Result.success(null));

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

        assertThat(result.isSuccess()).isTrue();
        var batch = result.unsafeGetValue();
        assertThat(batch.status()).isEqualTo(BatchStatus.PLANNED);
        assertThat(batch.batchNumber()).isEqualTo(BATCH_NUMBER);
        assertThat(batch.recipeId().value()).isEqualTo("recipe-1");
        verify(batchRepository).save(any(Batch.class));
    }

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

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

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

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

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

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(BatchError.ValidationFailure.class);
        assertThat(result.unsafeGetError().message()).contains("recipe-1");
        verify(batchRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when recipe is not ACTIVE")
    void should_Fail_When_RecipeNotActive() {
        when(authPort.can(performedBy, ProductionAction.BATCH_WRITE)).thenReturn(true);
        when(recipeRepository.findById(RecipeId.of("recipe-1")))
                .thenReturn(Result.success(Optional.of(draftRecipe())));

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

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

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

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

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

    @Test
    @DisplayName("should fail when batch number generation fails")
    void should_Fail_When_BatchNumberGenerationFails() {
        when(authPort.can(performedBy, ProductionAction.BATCH_WRITE)).thenReturn(true);
        when(recipeRepository.findById(RecipeId.of("recipe-1")))
                .thenReturn(Result.success(Optional.of(activeRecipe())));
        when(batchNumberGenerator.generateNext(PRODUCTION_DATE))
                .thenReturn(Result.failure(new BatchError.ValidationFailure("Sequence exhausted")));

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

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(BatchError.ValidationFailure.class);
        verify(batchRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when batch repository save fails")
    void should_Fail_When_BatchSaveFails() {
        when(authPort.can(performedBy, ProductionAction.BATCH_WRITE)).thenReturn(true);
        when(recipeRepository.findById(RecipeId.of("recipe-1")))
                .thenReturn(Result.success(Optional.of(activeRecipe())));
        when(batchNumberGenerator.generateNext(PRODUCTION_DATE))
                .thenReturn(Result.success(BATCH_NUMBER));
        when(batchRepository.save(any()))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("disk full")));

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

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

    @Test
    @DisplayName("should fail when planned quantity is invalid")
    void should_Fail_When_InvalidQuantity() {
        when(authPort.can(performedBy, ProductionAction.BATCH_WRITE)).thenReturn(true);
        when(recipeRepository.findById(RecipeId.of("recipe-1")))
                .thenReturn(Result.success(Optional.of(activeRecipe())));
        when(batchNumberGenerator.generateNext(PRODUCTION_DATE))
                .thenReturn(Result.success(BATCH_NUMBER));

        var cmd = new PlanBatchCommand("recipe-1", "0", "KILOGRAM", PRODUCTION_DATE, BEST_BEFORE_DATE);
        var result = planBatch.execute(cmd, performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(BatchError.InvalidPlannedQuantity.class);
        verify(batchRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when dates are invalid")
    void should_Fail_When_InvalidDates() {
        when(authPort.can(performedBy, ProductionAction.BATCH_WRITE)).thenReturn(true);
        when(recipeRepository.findById(RecipeId.of("recipe-1")))
                .thenReturn(Result.success(Optional.of(activeRecipe())));
        when(batchNumberGenerator.generateNext(LocalDate.of(2026, 6, 1)))
                .thenReturn(Result.success(BatchNumber.generate(LocalDate.of(2026, 6, 1), 1)));

        var cmd = new PlanBatchCommand("recipe-1", "100", "KILOGRAM",
                LocalDate.of(2026, 6, 1), LocalDate.of(2026, 3, 1));
        var result = planBatch.execute(cmd, performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(BatchError.InvalidDates.class);
        verify(batchRepository, never()).save(any());
    }
}
