package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.ReserveStockCommand;
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.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("ReserveStock Use Case")
class ReserveStockTest {

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

    private ReserveStock reserveStock;
    private ReserveStockCommand validCommand;
    private Stock existingStock;

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

        var batch = StockBatch.reconstitute(
                StockBatchId.generate(),
                new BatchReference("BATCH-001", BatchType.PRODUCED),
                Quantity.reconstitute(new BigDecimal("50"), UnitOfMeasure.KILOGRAM),
                LocalDate.of(2026, 12, 31),
                StockBatchStatus.AVAILABLE,
                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 ReserveStockCommand(
                "stock-1", "PRODUCTION_ORDER", "PO-001", "10", "KILOGRAM", "NORMAL"
        );
    }

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

        var result = reserveStock.execute(validCommand);

        assertThat(result.isSuccess()).isTrue();
        var reservation = result.unsafeGetValue();
        assertThat(reservation.referenceType()).isEqualTo(ReferenceType.PRODUCTION_ORDER);
        assertThat(reservation.referenceId()).isEqualTo("PO-001");
        assertThat(reservation.quantity().amount()).isEqualByComparingTo(new BigDecimal("10"));
        assertThat(reservation.priority()).isEqualTo(ReservationPriority.NORMAL);
        assertThat(reservation.allocations()).isNotEmpty();
        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 = reserveStock.execute(validCommand);

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

    @Test
    @DisplayName("should fail with StockNotFound when stockId is null")
    void shouldFailWhenStockIdNull() {
        var cmd = new ReserveStockCommand(null, "PRODUCTION_ORDER", "PO-001", "10", "KILOGRAM", "NORMAL");

        var result = reserveStock.execute(cmd);

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

    @Test
    @DisplayName("should fail with StockNotFound when stockId is blank")
    void shouldFailWhenStockIdBlank() {
        var cmd = new ReserveStockCommand("", "PRODUCTION_ORDER", "PO-001", "10", "KILOGRAM", "NORMAL");

        var result = reserveStock.execute(cmd);

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

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

    @Test
    @DisplayName("should propagate InsufficientStock from domain")
    void shouldPropagateInsufficientStock() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));

        var cmd = new ReserveStockCommand("stock-1", "PRODUCTION_ORDER", "PO-001", "999", "KILOGRAM", "NORMAL");
        var result = reserveStock.execute(cmd);

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

    @Test
    @DisplayName("should propagate InvalidReferenceType from domain")
    void shouldPropagateInvalidReferenceType() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));

        var cmd = new ReserveStockCommand("stock-1", "INVALID_TYPE", "PO-001", "10", "KILOGRAM", "NORMAL");
        var result = reserveStock.execute(cmd);

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

    @Test
    @DisplayName("should propagate InvalidReservationPriority from domain")
    void shouldPropagateInvalidPriority() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));

        var cmd = new ReserveStockCommand("stock-1", "PRODUCTION_ORDER", "PO-001", "10", "KILOGRAM", "SUPER_HIGH");
        var result = reserveStock.execute(cmd);

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

    @Test
    @DisplayName("should propagate InvalidQuantity from domain")
    void shouldPropagateInvalidQuantity() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));

        var cmd = new ReserveStockCommand("stock-1", "PRODUCTION_ORDER", "PO-001", "-5", "KILOGRAM", "NORMAL");
        var result = reserveStock.execute(cmd);

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