package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.ReleaseReservationCommand;
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("ReleaseReservation Use Case")
class ReleaseReservationTest {

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

    private ReleaseReservation releaseReservation;
    private Stock existingStock;
    private String reservationId;

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

        // Create a reservation
        var reserveResult = existingStock.reserve(
                new ReservationDraft("PRODUCTION_ORDER", "PO-001", "10", "KILOGRAM", "NORMAL"));
        reservationId = reserveResult.unsafeGetValue().id().value();
    }

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

        var result = releaseReservation.execute(new ReleaseReservationCommand("stock-1", reservationId));

        assertThat(result.isSuccess()).isTrue();
        assertThat(existingStock.reservations()).isEmpty();
        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 = releaseReservation.execute(new ReleaseReservationCommand("stock-1", reservationId));

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

    @Test
    @DisplayName("should fail with ReservationNotFound when reservation does not exist in stock")
    void shouldFailWhenReservationNotFoundInStock() {
        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));

        var result = releaseReservation.execute(new ReleaseReservationCommand("stock-1", "nonexistent"));

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(StockError.ReservationNotFound.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 = releaseReservation.execute(new ReleaseReservationCommand("stock-1", reservationId));

        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 = releaseReservation.execute(new ReleaseReservationCommand("stock-1", reservationId));

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

    @Test
    @DisplayName("should release only targeted reservation when stock has multiple")
    void shouldReleaseOnlyTargetedReservation() {
        // Add a second reservation
        var res2 = existingStock.reserve(
                new ReservationDraft("SALE_ORDER", "SO-001", "5", "KILOGRAM", "URGENT"));
        var secondReservationId = res2.unsafeGetValue().id().value();
        assertThat(existingStock.reservations()).hasSize(2);

        when(stockRepository.findById(StockId.of("stock-1")))
                .thenReturn(Result.success(Optional.of(existingStock)));
        when(stockRepository.save(any())).thenReturn(Result.success(null));

        var result = releaseReservation.execute(new ReleaseReservationCommand("stock-1", reservationId));

        assertThat(result.isSuccess()).isTrue();
        assertThat(existingStock.reservations()).hasSize(1);
        assertThat(existingStock.reservations().getFirst().id().value()).isEqualTo(secondReservationId);
        verify(stockRepository).save(existingStock);
    }
}
