package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.BookProductionOutputCommand;
import de.effigenix.domain.inventory.*;
import de.effigenix.domain.masterdata.article.ArticleId;
import de.effigenix.shared.common.RepositoryError;
import de.effigenix.shared.common.Result;
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.util.List;
import java.util.Optional;
import java.util.function.Supplier;

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

@ExtendWith(MockitoExtension.class)
@DisplayName("BookProductionOutput Use Case")
class BookProductionOutputTest {

    @Mock private StockRepository stockRepository;
    @Mock private StorageLocationRepository storageLocationRepository;
    @Mock private StockMovementRepository stockMovementRepository;
    @Mock private UnitOfWork unitOfWork;

    private BookProductionOutput bookProductionOutput;

    @BeforeEach
    void setUp() {
        bookProductionOutput = new BookProductionOutput(stockRepository, storageLocationRepository,
                stockMovementRepository, unitOfWork);
        lenient().when(unitOfWork.executeAtomically(any())).thenAnswer(inv -> ((Supplier<?>) inv.getArgument(0)).get());
    }

    private StorageLocation activeProductionArea() {
        return StorageLocation.reconstitute(
                StorageLocationId.of("loc-prod"),
                StorageLocationName.of("Produktion").unsafeGetValue(),
                StorageType.PRODUCTION_AREA,
                null,
                true
        );
    }

    private StorageLocation inactiveProductionArea() {
        return StorageLocation.reconstitute(
                StorageLocationId.of("loc-prod-inactive"),
                StorageLocationName.of("Produktion Alt").unsafeGetValue(),
                StorageType.PRODUCTION_AREA,
                null,
                false
        );
    }

    private Stock existingStock(String articleId, String locationId) {
        return Stock.reconstitute(
                StockId.of("stock-1"),
                ArticleId.of(articleId),
                StorageLocationId.of(locationId),
                null, null,
                List.of(), List.of()
        );
    }

    private BookProductionOutputCommand validCommand() {
        return new BookProductionOutputCommand(
                "P-2026-03-01-001", "article-42", "95", "KILOGRAM", "2026-06-01");
    }

    @Test
    @DisplayName("should book production output when stock exists")
    void should_BookOutput_When_StockExists() {
        var location = activeProductionArea();
        var stock = existingStock("article-42", "loc-prod");
        when(storageLocationRepository.findByStorageType(StorageType.PRODUCTION_AREA))
                .thenReturn(Result.success(List.of(location)));
        when(stockRepository.findByArticleIdAndStorageLocationId(ArticleId.of("article-42"), StorageLocationId.of("loc-prod")))
                .thenReturn(Result.success(Optional.of(stock)));
        when(stockRepository.save(any())).thenReturn(Result.success(null));
        when(stockMovementRepository.save(any())).thenReturn(Result.success(null));

        var result = bookProductionOutput.execute(validCommand());

        assertThat(result.isSuccess()).isTrue();
        verify(stockRepository, times(1)).save(stock);
        verify(stockMovementRepository).save(any(StockMovement.class));
    }

    @Test
    @DisplayName("should auto-create stock when none exists")
    void should_CreateStock_When_NoneExists() {
        var location = activeProductionArea();
        when(storageLocationRepository.findByStorageType(StorageType.PRODUCTION_AREA))
                .thenReturn(Result.success(List.of(location)));
        when(stockRepository.findByArticleIdAndStorageLocationId(any(), any()))
                .thenReturn(Result.success(Optional.empty()));
        when(stockRepository.save(any())).thenReturn(Result.success(null));
        when(stockMovementRepository.save(any())).thenReturn(Result.success(null));

        var result = bookProductionOutput.execute(validCommand());

        assertThat(result.isSuccess()).isTrue();
        // save called twice: once for new stock creation, once after addBatch
        verify(stockRepository, times(2)).save(any(Stock.class));
        verify(stockMovementRepository).save(any(StockMovement.class));
    }

    @Test
    @DisplayName("should fail when no active PRODUCTION_AREA exists")
    void should_Fail_When_NoProductionArea() {
        when(storageLocationRepository.findByStorageType(StorageType.PRODUCTION_AREA))
                .thenReturn(Result.success(List.of()));

        var result = bookProductionOutput.execute(validCommand());

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOutputError.NoProductionArea.class);
        verify(stockRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when only inactive PRODUCTION_AREA exists")
    void should_Fail_When_OnlyInactiveProductionArea() {
        when(storageLocationRepository.findByStorageType(StorageType.PRODUCTION_AREA))
                .thenReturn(Result.success(List.of(inactiveProductionArea())));

        var result = bookProductionOutput.execute(validCommand());

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOutputError.NoProductionArea.class);
    }

    @Test
    @DisplayName("should fail with RepositoryFailure when storage location lookup fails")
    void should_Fail_When_StorageLocationLookupFails() {
        when(storageLocationRepository.findByStorageType(StorageType.PRODUCTION_AREA))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("connection lost")));

        var result = bookProductionOutput.execute(validCommand());

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

    @Test
    @DisplayName("should fail with RepositoryFailure when stock lookup fails")
    void should_Fail_When_StockLookupFails() {
        var location = activeProductionArea();
        when(storageLocationRepository.findByStorageType(StorageType.PRODUCTION_AREA))
                .thenReturn(Result.success(List.of(location)));
        when(stockRepository.findByArticleIdAndStorageLocationId(any(), any()))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("read error")));

        var result = bookProductionOutput.execute(validCommand());

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