package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.CompleteInventoryCountCommand;
import de.effigenix.domain.inventory.*;
import de.effigenix.domain.masterdata.article.ArticleId;
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.Instant;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

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

@ExtendWith(MockitoExtension.class)
@DisplayName("CompleteInventoryCount Use Case")
class CompleteInventoryCountTest {

    @Mock private InventoryCountRepository inventoryCountRepository;
    @Mock private StockRepository stockRepository;
    @Mock private StockMovementRepository stockMovementRepository;
    @Mock private UnitOfWork unitOfWork;
    @Mock private AuthorizationPort authPort;

    private CompleteInventoryCount completeInventoryCount;
    private InventoryCountReconciliationService reconciliationService;
    private final ActorId actorId = ActorId.of("user-2");

    @BeforeEach
    void setUp() {
        reconciliationService = new InventoryCountReconciliationService();
        completeInventoryCount = new CompleteInventoryCount(
                inventoryCountRepository, stockRepository, stockMovementRepository,
                reconciliationService, unitOfWork, authPort
        );
        lenient().when(authPort.can(any(ActorId.class), any())).thenReturn(true);
    }

    private void stubUnitOfWork() {
        when(unitOfWork.executeAtomically(any())).thenAnswer(invocation -> {
            @SuppressWarnings("unchecked")
            var supplier = (java.util.function.Supplier<Result<?, ?>>) invocation.getArgument(0);
            return supplier.get();
        });
    }

    // ==================== Happy Path ====================

    @Test
    @DisplayName("should complete inventory count with adjustment movements")
    void shouldCompleteWithAdjustments() {
        stubUnitOfWork();
        var count = createCountingCountAllCounted("10.0", "8.0");
        var stocks = List.of(stockFor("article-1", "stock-1"));

        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.success(Optional.of(count)));
        when(stockRepository.findAllByStorageLocationId(StorageLocationId.of("location-1")))
                .thenReturn(Result.success(stocks));
        when(inventoryCountRepository.save(any())).thenReturn(Result.success(null));
        when(stockMovementRepository.save(any())).thenReturn(Result.success(null));

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

        assertThat(result.isSuccess()).isTrue();
        assertThat(result.unsafeGetValue().status()).isEqualTo(InventoryCountStatus.COMPLETED);
        assertThat(result.unsafeGetValue().completedBy()).isEqualTo("user-2");
        verify(inventoryCountRepository).save(any(InventoryCount.class));
        verify(stockMovementRepository).save(any(StockMovement.class));
    }

    @Test
    @DisplayName("should complete with no movements when no deviations")
    void shouldCompleteWithNoMovementsWhenNoDeviations() {
        stubUnitOfWork();
        var count = createCountingCountAllCounted("10.0", "10.0");
        var stocks = List.of(stockFor("article-1", "stock-1"));

        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.success(Optional.of(count)));
        when(stockRepository.findAllByStorageLocationId(StorageLocationId.of("location-1")))
                .thenReturn(Result.success(stocks));
        when(inventoryCountRepository.save(any())).thenReturn(Result.success(null));

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

        assertThat(result.isSuccess()).isTrue();
        assertThat(result.unsafeGetValue().status()).isEqualTo(InventoryCountStatus.COMPLETED);
        verify(inventoryCountRepository).save(any(InventoryCount.class));
        verify(stockMovementRepository, never()).save(any());
    }

    @Test
    @DisplayName("should create IN movement for positive deviation")
    void shouldCreateInMovementForPositiveDeviation() {
        stubUnitOfWork();
        var count = createCountingCountAllCounted("10.0", "15.0");
        var stocks = List.of(stockFor("article-1", "stock-1"));

        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.success(Optional.of(count)));
        when(stockRepository.findAllByStorageLocationId(StorageLocationId.of("location-1")))
                .thenReturn(Result.success(stocks));
        when(inventoryCountRepository.save(any())).thenReturn(Result.success(null));
        when(stockMovementRepository.save(any())).thenReturn(Result.success(null));

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

        assertThat(result.isSuccess()).isTrue();
        verify(stockMovementRepository).save(argThat(movement ->
                movement.direction() == MovementDirection.IN
                        && movement.quantity().amount().compareTo(new BigDecimal("5.0")) == 0
                        && movement.movementType() == MovementType.ADJUSTMENT
        ));
    }

    @Test
    @DisplayName("should create OUT movement for negative deviation")
    void shouldCreateOutMovementForNegativeDeviation() {
        stubUnitOfWork();
        var count = createCountingCountAllCounted("10.0", "7.0");
        var stocks = List.of(stockFor("article-1", "stock-1"));

        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.success(Optional.of(count)));
        when(stockRepository.findAllByStorageLocationId(StorageLocationId.of("location-1")))
                .thenReturn(Result.success(stocks));
        when(inventoryCountRepository.save(any())).thenReturn(Result.success(null));
        when(stockMovementRepository.save(any())).thenReturn(Result.success(null));

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

        assertThat(result.isSuccess()).isTrue();
        verify(stockMovementRepository).save(argThat(movement ->
                movement.direction() == MovementDirection.OUT
                        && movement.quantity().amount().compareTo(new BigDecimal("3.0")) == 0
        ));
    }

    // ==================== Authorization ====================

    @Test
    @DisplayName("should fail when not authorized")
    void shouldFailWhenNotAuthorized() {
        when(authPort.can(any(ActorId.class), any())).thenReturn(false);

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(InventoryCountError.Unauthorized.class);
        verify(inventoryCountRepository, never()).findById(any());
    }

    // ==================== Input Validation ====================

    @Test
    @DisplayName("should fail when inventory count ID is blank")
    void shouldFailWhenIdBlank() {
        var cmd = new CompleteInventoryCountCommand("", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(InventoryCountError.InvalidInventoryCountId.class);
    }

    @Test
    @DisplayName("should fail when inventory count ID is null")
    void shouldFailWhenIdNull() {
        var cmd = new CompleteInventoryCountCommand(null, "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(InventoryCountError.InvalidInventoryCountId.class);
    }

    // ==================== Not Found ====================

    @Test
    @DisplayName("should fail when inventory count not found")
    void shouldFailWhenNotFound() {
        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.success(Optional.empty()));

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(InventoryCountError.InventoryCountNotFound.class);
    }

    // ==================== Domain Validation Errors ====================

    @Test
    @DisplayName("should fail when same person violation (Vier-Augen-Prinzip)")
    void shouldFailWhenSamePerson() {
        var count = createCountingCountAllCounted("10.0", "8.0");

        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.success(Optional.of(count)));

        // completedBy = initiatedBy = "user-1"
        var cmd = new CompleteInventoryCountCommand("count-1", "user-1");
        var result = completeInventoryCount.execute(cmd, ActorId.of("user-1"));

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(InventoryCountError.SamePersonViolation.class);
    }

    @Test
    @DisplayName("should fail when count items are incomplete")
    void shouldFailWhenIncompleteItems() {
        var items = new ArrayList<>(List.of(
                CountItem.reconstitute(CountItemId.of("item-1"), ArticleId.of("article-1"),
                        Quantity.reconstitute(new BigDecimal("10.0"), UnitOfMeasure.KILOGRAM), null)
        ));
        var count = InventoryCount.reconstitute(
                InventoryCountId.of("count-1"), StorageLocationId.of("location-1"),
                LocalDate.now(), "user-1", null, InventoryCountStatus.COUNTING,
                null, Instant.now(), items
        );

        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.success(Optional.of(count)));

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(InventoryCountError.IncompleteCountItems.class);
    }

    @Test
    @DisplayName("should fail when count is not in COUNTING status")
    void shouldFailWhenWrongStatus() {
        var count = InventoryCount.reconstitute(
                InventoryCountId.of("count-1"), StorageLocationId.of("location-1"),
                LocalDate.now(), "user-1", null, InventoryCountStatus.OPEN,
                null, Instant.now(), new ArrayList<>()
        );

        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.success(Optional.of(count)));

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(InventoryCountError.InvalidStatusTransition.class);
    }

    // ==================== Repository Failures ====================

    @Test
    @DisplayName("should fail when findById repository fails")
    void shouldFailWhenFindByIdFails() {
        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("connection lost")));

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

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

    @Test
    @DisplayName("should fail when stock repository fails")
    void shouldFailWhenStockRepositoryFails() {
        var count = createCountingCountAllCounted("10.0", "8.0");

        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.success(Optional.of(count)));
        when(stockRepository.findAllByStorageLocationId(StorageLocationId.of("location-1")))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("stock db error")));

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

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

    @Test
    @DisplayName("should fail when inventory count save fails")
    void shouldFailWhenSaveFails() {
        stubUnitOfWork();
        var count = createCountingCountAllCounted("10.0", "10.0");
        var stocks = List.of(stockFor("article-1", "stock-1"));

        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.success(Optional.of(count)));
        when(stockRepository.findAllByStorageLocationId(StorageLocationId.of("location-1")))
                .thenReturn(Result.success(stocks));
        when(inventoryCountRepository.save(any()))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("save failed")));

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

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

    @Test
    @DisplayName("should fail when stock movement save fails")
    void shouldFailWhenMovementSaveFails() {
        stubUnitOfWork();
        var count = createCountingCountAllCounted("10.0", "8.0");
        var stocks = List.of(stockFor("article-1", "stock-1"));

        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.success(Optional.of(count)));
        when(stockRepository.findAllByStorageLocationId(StorageLocationId.of("location-1")))
                .thenReturn(Result.success(stocks));
        when(inventoryCountRepository.save(any())).thenReturn(Result.success(null));
        when(stockMovementRepository.save(any()))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("movement save failed")));

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

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

    @Test
    @DisplayName("should fail when stock not found for deviating article")
    void shouldFailWhenStockNotFoundForArticle() {
        var count = createCountingCountAllCounted("10.0", "8.0");

        when(inventoryCountRepository.findById(InventoryCountId.of("count-1")))
                .thenReturn(Result.success(Optional.of(count)));
        when(stockRepository.findAllByStorageLocationId(StorageLocationId.of("location-1")))
                .thenReturn(Result.success(List.of()));

        var cmd = new CompleteInventoryCountCommand("count-1", "user-2");
        var result = completeInventoryCount.execute(cmd, actorId);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(InventoryCountError.StockNotFoundForArticle.class);
    }

    // ==================== Helpers ====================

    private InventoryCount createCountingCountAllCounted(String expected, String actual) {
        var items = new ArrayList<>(List.of(
                CountItem.reconstitute(CountItemId.of("item-1"), ArticleId.of("article-1"),
                        Quantity.reconstitute(new BigDecimal(expected), UnitOfMeasure.KILOGRAM),
                        Quantity.reconstitute(new BigDecimal(actual), UnitOfMeasure.KILOGRAM))
        ));
        return InventoryCount.reconstitute(
                InventoryCountId.of("count-1"), StorageLocationId.of("location-1"),
                LocalDate.now(), "user-1", null, InventoryCountStatus.COUNTING,
                null, Instant.now(), items
        );
    }

    private Stock stockFor(String articleId, String stockId) {
        var batch = StockBatch.reconstitute(
                StockBatchId.of("batch-1"),
                new BatchReference("BATCH-001", BatchType.PRODUCED),
                Quantity.reconstitute(new BigDecimal("100.0"), UnitOfMeasure.KILOGRAM),
                LocalDate.now().plusDays(30),
                StockBatchStatus.AVAILABLE,
                Instant.now()
        );
        return Stock.reconstitute(
                StockId.of(stockId), ArticleId.of(articleId),
                StorageLocationId.of("location-1"), null, null,
                List.of(batch), List.of()
        );
    }
}
