package de.effigenix.application.production;

import de.effigenix.domain.production.*;
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.security.ActorId;
import de.effigenix.shared.security.AuthorizationPort;
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.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
@DisplayName("FindBatchByNumber Use Case")
class FindBatchByNumberTest {

    @Mock private BatchRepository batchRepository;
    @Mock private AuthorizationPort authPort;

    private FindBatchByNumber findBatchByNumber;
    private ActorId performedBy;

    private static final BatchNumber BATCH_NUMBER = BatchNumber.generate(LocalDate.of(2026, 3, 1), 1);

    @BeforeEach
    void setUp() {
        findBatchByNumber = new FindBatchByNumber(batchRepository, authPort);
        performedBy = ActorId.of("admin-user");
    }

    private Batch sampleBatch() {
        return Batch.reconstitute(
                BatchId.of("batch-1"),
                BATCH_NUMBER,
                RecipeId.of("recipe-1"),
                BatchStatus.PLANNED,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                null, null, null,
                LocalDate.of(2026, 3, 1),
                LocalDate.of(2026, 6, 1),
                OffsetDateTime.now(ZoneOffset.UTC),
                OffsetDateTime.now(ZoneOffset.UTC),
                null,
                null, null,
                0L, List.of()
        );
    }

    @Test
    @DisplayName("should return batch when batch number exists")
    void should_ReturnBatch_When_BatchNumberExists() {
        when(authPort.can(performedBy, ProductionAction.BATCH_READ)).thenReturn(true);
        when(batchRepository.findByBatchNumber(BATCH_NUMBER)).thenReturn(Result.success(Optional.of(sampleBatch())));

        var result = findBatchByNumber.execute(BATCH_NUMBER, performedBy);

        assertThat(result.isSuccess()).isTrue();
        assertThat(result.unsafeGetValue().batchNumber()).isEqualTo(BATCH_NUMBER);
    }

    @Test
    @DisplayName("should fail with BatchNotFoundByNumber when batch number does not exist")
    void should_FailWithBatchNotFoundByNumber_When_BatchNumberDoesNotExist() {
        when(authPort.can(performedBy, ProductionAction.BATCH_READ)).thenReturn(true);
        when(batchRepository.findByBatchNumber(BATCH_NUMBER)).thenReturn(Result.success(Optional.empty()));

        var result = findBatchByNumber.execute(BATCH_NUMBER, performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(BatchError.BatchNotFoundByNumber.class);
    }

    @Test
    @DisplayName("should fail with RepositoryFailure when repository returns error")
    void should_FailWithRepositoryFailure_When_RepositoryReturnsError() {
        when(authPort.can(performedBy, ProductionAction.BATCH_READ)).thenReturn(true);
        when(batchRepository.findByBatchNumber(BATCH_NUMBER))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("connection lost")));

        var result = findBatchByNumber.execute(BATCH_NUMBER, performedBy);

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

    @Test
    @DisplayName("should fail with Unauthorized when actor lacks permission")
    void should_FailWithUnauthorized_When_ActorLacksPermission() {
        when(authPort.can(performedBy, ProductionAction.BATCH_READ)).thenReturn(false);

        var result = findBatchByNumber.execute(BATCH_NUMBER, performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(BatchError.Unauthorized.class);
        verify(batchRepository, never()).findByBatchNumber(any());
    }
}
