package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.AddStockBatchCommand;
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 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.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("AddStockBatch Use Case")
class AddStockBatchTest {

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

    private AddStockBatch addStockBatch;
    private AddStockBatchCommand validCommand;
    private Stock existingStock;

    @BeforeEach
    void setUp() {
        addStockBatch = new AddStockBatch(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()
        );

        validCommand = new AddStockBatchCommand(
                "stock-1", "BATCH-001", "PRODUCED", "10.5", "KILOGRAM", "2026-12-31"
        );
    }

    @Test
    @DisplayName("should add batch to existing stock")
    void shouldAddBatchToExistingStock() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));
        when(stockRepository.save(any())).thenReturn(Result.success(null));

        var result = addStockBatch.execute(validCommand);

        assertThat(result.isSuccess()).isTrue();
        var batch = result.unsafeGetValue();
        assertThat(batch.batchReference().batchId()).isEqualTo("BATCH-001");
        assertThat(batch.batchReference().batchType()).isEqualTo(BatchType.PRODUCED);
        assertThat(batch.quantity().amount()).isEqualByComparingTo(new BigDecimal("10.5"));
        assertThat(batch.status()).isEqualTo(StockBatchStatus.AVAILABLE);
        assertThat(batch.receivedAt()).isNotNull();
        verify(stockRepository).save(existingStock);
    }

    @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 result = addStockBatch.execute(validCommand);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(StockError.StockNotFound.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 result = addStockBatch.execute(validCommand);

        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 result = addStockBatch.execute(validCommand);

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

    @Test
    @DisplayName("should fail with DuplicateBatchReference when batch already exists")
    void shouldFailWhenDuplicateBatchReference() {
        var stockWithBatch = Stock.reconstitute(
                StockId.of("stock-1"),
                ArticleId.of("article-1"),
                StorageLocationId.of("location-1"),
                null, null,
                List.of(StockBatch.reconstitute(
                        StockBatchId.generate(),
                        new BatchReference("BATCH-001", BatchType.PRODUCED),
                        Quantity.reconstitute(new BigDecimal("5"), UnitOfMeasure.KILOGRAM),
                        LocalDate.of(2026, 12, 31),
                        StockBatchStatus.AVAILABLE,
                        Instant.now()
                )), List.of()
        );

        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(stockWithBatch)));

        var result = addStockBatch.execute(validCommand);

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

    @Test
    @DisplayName("should fail with InvalidBatchReference when batchType is invalid")
    void shouldFailWhenInvalidBatchType() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));

        var cmd = new AddStockBatchCommand("stock-1", "BATCH-001", "INVALID", "10", "KILOGRAM", "2026-12-31");
        var result = addStockBatch.execute(cmd);

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

    @Test
    @DisplayName("should fail with InvalidQuantity when quantity is negative")
    void shouldFailWhenInvalidQuantity() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));

        var cmd = new AddStockBatchCommand("stock-1", "BATCH-001", "PRODUCED", "-1", "KILOGRAM", "2026-12-31");
        var result = addStockBatch.execute(cmd);

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

    @Test
    @DisplayName("should fail with InvalidExpiryDate when date format is wrong")
    void shouldFailWhenInvalidExpiryDate() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));

        var cmd = new AddStockBatchCommand("stock-1", "BATCH-001", "PRODUCED", "10", "KILOGRAM", "not-a-date");
        var result = addStockBatch.execute(cmd);

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