package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.UpdateStockCommand;
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.common.UnitOfMeasure;
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 static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.lenient;

@ExtendWith(MockitoExtension.class)
@DisplayName("UpdateStock Use Case")
class UpdateStockTest {

    @Mock private StockRepository stockRepository;
    @Mock private UnitOfWork unitOfWork;

    private UpdateStock updateStock;
    private Stock existingStock;

    @BeforeEach
    void setUp() {
        updateStock = new UpdateStock(stockRepository, unitOfWork);
        lenient().when(unitOfWork.executeAtomically(any())).thenAnswer(inv -> ((java.util.function.Supplier<?>) inv.getArgument(0)).get());

        existingStock = Stock.reconstitute(
                StockId.of("stock-1"),
                ArticleId.of("article-1"),
                StorageLocationId.of("location-1"),
                null, null,
                List.of(), List.of()
        );
    }

    @Test
    @DisplayName("should update minimumLevel successfully")
    void shouldUpdateMinimumLevel() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));
        when(stockRepository.save(any())).thenReturn(Result.success(null));

        var cmd = new UpdateStockCommand("stock-1", "50", "KILOGRAM", null);
        var result = updateStock.execute(cmd);

        assertThat(result.isSuccess()).isTrue();
        var stock = result.unsafeGetValue();
        assertThat(stock.minimumLevel()).isNotNull();
        assertThat(stock.minimumLevel().quantity().amount().intValue()).isEqualTo(50);
        assertThat(stock.minimumLevel().quantity().uom()).isEqualTo(UnitOfMeasure.KILOGRAM);
        assertThat(stock.minimumShelfLife()).isNull();
        verify(stockRepository).save(existingStock);
    }

    @Test
    @DisplayName("should update minimumShelfLife successfully")
    void shouldUpdateMinimumShelfLife() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));
        when(stockRepository.save(any())).thenReturn(Result.success(null));

        var cmd = new UpdateStockCommand("stock-1", null, null, 30);
        var result = updateStock.execute(cmd);

        assertThat(result.isSuccess()).isTrue();
        var stock = result.unsafeGetValue();
        assertThat(stock.minimumShelfLife()).isNotNull();
        assertThat(stock.minimumShelfLife().days()).isEqualTo(30);
        assertThat(stock.minimumLevel()).isNull();
        verify(stockRepository).save(existingStock);
    }

    @Test
    @DisplayName("should update both parameters at once")
    void shouldUpdateBothParameters() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));
        when(stockRepository.save(any())).thenReturn(Result.success(null));

        var cmd = new UpdateStockCommand("stock-1", "100", "LITER", 14);
        var result = updateStock.execute(cmd);

        assertThat(result.isSuccess()).isTrue();
        var stock = result.unsafeGetValue();
        assertThat(stock.minimumLevel()).isNotNull();
        assertThat(stock.minimumLevel().quantity().uom()).isEqualTo(UnitOfMeasure.LITER);
        assertThat(stock.minimumShelfLife()).isNotNull();
        assertThat(stock.minimumShelfLife().days()).isEqualTo(14);
    }

    @Test
    @DisplayName("should not change fields when null in command")
    void shouldNotChangeFieldsWhenNull() {
        var stockWithParams = Stock.reconstitute(
                StockId.of("stock-1"),
                ArticleId.of("article-1"),
                StorageLocationId.of("location-1"),
                MinimumLevel.of("25", "KILOGRAM").unsafeGetValue(),
                MinimumShelfLife.of(7).unsafeGetValue(),
                List.of(), List.of()
        );
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(stockWithParams)));
        when(stockRepository.save(any())).thenReturn(Result.success(null));

        var cmd = new UpdateStockCommand("stock-1", null, null, null);
        var result = updateStock.execute(cmd);

        assertThat(result.isSuccess()).isTrue();
        var stock = result.unsafeGetValue();
        assertThat(stock.minimumLevel().quantity().amount().intValue()).isEqualTo(25);
        assertThat(stock.minimumShelfLife().days()).isEqualTo(7);
    }

    @Test
    @DisplayName("should fail with StockNotFound when stock does not exist")
    void shouldFailWhenStockNotFound() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.empty()));

        var cmd = new UpdateStockCommand("stock-1", "50", "KILOGRAM", null);
        var result = updateStock.execute(cmd);

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

    @Test
    @DisplayName("should fail with InvalidMinimumLevel for invalid amount")
    void shouldFailForInvalidMinimumLevel() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));

        var cmd = new UpdateStockCommand("stock-1", "-5", "KILOGRAM", null);
        var result = updateStock.execute(cmd);

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

    @Test
    @DisplayName("should fail with InvalidMinimumShelfLife for zero days")
    void shouldFailForInvalidMinimumShelfLife() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));

        var cmd = new UpdateStockCommand("stock-1", null, null, 0);
        var result = updateStock.execute(cmd);

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

    @Test
    @DisplayName("should fail with RepositoryFailure when findById fails")
    void shouldFailWhenFindByIdFails() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("connection lost")));

        var cmd = new UpdateStockCommand("stock-1", "50", "KILOGRAM", null);
        var result = updateStock.execute(cmd);

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

    @Test
    @DisplayName("should fail with RepositoryFailure when save fails")
    void shouldFailWhenSaveFails() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));
        when(stockRepository.save(any()))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("connection lost")));

        var cmd = new UpdateStockCommand("stock-1", "50", "KILOGRAM", null);
        var result = updateStock.execute(cmd);

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