package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.UnblockStockBatchCommand;
import de.effigenix.application.usermanagement.AuditLogger;
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 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("UnblockStockBatch Use Case")
class UnblockStockBatchTest {

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

    private UnblockStockBatch unblockStockBatch;
    private StockBatchId batchId;
    private Stock existingStock;
    private UnblockStockBatchCommand validCommand;
    private final ActorId actor = ActorId.of("test-user");

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

        batchId = StockBatchId.of("batch-1");
        var batch = StockBatch.reconstitute(
                batchId,
                new BatchReference("BATCH-001", BatchType.PRODUCED),
                Quantity.reconstitute(new BigDecimal("10"), UnitOfMeasure.KILOGRAM, null, null),
                LocalDate.of(2026, 12, 31),
                StockBatchStatus.BLOCKED,
                Instant.now()
        );

        existingStock = Stock.reconstitute(
                StockId.of("stock-1"),
                ArticleId.of("article-1"),
                StorageLocationId.of("location-1"),
                null, null,
                new ArrayList<>(List.of(batch)), List.of()
        );

        validCommand = new UnblockStockBatchCommand("stock-1", "batch-1");
    }

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

        var result = unblockStockBatch.execute(validCommand, actor);

        assertThat(result.isSuccess()).isTrue();
        verify(stockRepository).save(existingStock);
        assertThat(existingStock.batches().getFirst().status()).isEqualTo(StockBatchStatus.AVAILABLE);
        verify(auditLogger).log(any(), eq("batch-1"), eq(actor));
    }

    @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 = unblockStockBatch.execute(validCommand, actor);

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

    @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 = unblockStockBatch.execute(validCommand, actor);

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

    @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 = unblockStockBatch.execute(validCommand, actor);

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

    @Test
    @DisplayName("should propagate domain error for batch not found")
    void shouldPropagateBatchNotFound() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));

        var cmd = new UnblockStockBatchCommand("stock-1", "nonexistent");
        var result = unblockStockBatch.execute(cmd, actor);

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

    @Test
    @DisplayName("should propagate BatchNotBlocked when batch is not blocked")
    void shouldPropagateBatchNotBlocked() {
        var availableBatch = StockBatch.reconstitute(
                batchId,
                new BatchReference("BATCH-001", BatchType.PRODUCED),
                Quantity.reconstitute(new BigDecimal("10"), UnitOfMeasure.KILOGRAM, null, null),
                LocalDate.of(2026, 12, 31),
                StockBatchStatus.AVAILABLE,
                Instant.now()
        );
        var stock = Stock.reconstitute(
                StockId.of("stock-1"),
                ArticleId.of("article-1"),
                StorageLocationId.of("location-1"),
                null, null,
                new ArrayList<>(List.of(availableBatch)), List.of()
        );
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(stock)));

        var result = unblockStockBatch.execute(validCommand, actor);

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