package de.effigenix.application.production;

import de.effigenix.application.production.command.StartProductionOrderCommand;
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 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.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;

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

@ExtendWith(MockitoExtension.class)
@DisplayName("StartProductionOrder Use Case")
class StartProductionOrderTest {

    @Mock private ProductionOrderRepository productionOrderRepository;
    @Mock private BatchRepository batchRepository;
    @Mock private AuthorizationPort authPort;
    @Mock private UnitOfWork unitOfWork;

    private StartProductionOrder startProductionOrder;
    private ActorId performedBy;

    private static final LocalDate PLANNED_DATE = LocalDate.now().plusDays(7);

    @BeforeEach
    void setUp() {
        startProductionOrder = new StartProductionOrder(productionOrderRepository, batchRepository, authPort, unitOfWork);
        performedBy = ActorId.of("admin-user");
        lenient().when(unitOfWork.executeAtomically(any())).thenAnswer(inv -> ((Supplier<?>) inv.getArgument(0)).get());
    }

    private StartProductionOrderCommand validCommand() {
        return new StartProductionOrderCommand("order-1", "batch-1");
    }

    private ProductionOrder releasedOrder() {
        return ProductionOrder.reconstitute(
                ProductionOrderId.of("order-1"),
                RecipeId.of("recipe-1"),
                ProductionOrderStatus.RELEASED,
                null,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                PLANNED_DATE,
                Priority.NORMAL,
                null,
                null,
                OffsetDateTime.now(ZoneOffset.UTC),
                OffsetDateTime.now(ZoneOffset.UTC),
                1L
        );
    }

    private ProductionOrder plannedOrder() {
        return ProductionOrder.reconstitute(
                ProductionOrderId.of("order-1"),
                RecipeId.of("recipe-1"),
                ProductionOrderStatus.PLANNED,
                null,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                PLANNED_DATE,
                Priority.NORMAL,
                null,
                null,
                OffsetDateTime.now(ZoneOffset.UTC),
                OffsetDateTime.now(ZoneOffset.UTC),
                1L
        );
    }

    private Batch plannedBatch() {
        return Batch.reconstitute(
                BatchId.of("batch-1"),
                new BatchNumber("P-2026-02-24-001"),
                RecipeId.of("recipe-1"),
                BatchStatus.PLANNED,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                null, null, null,
                PLANNED_DATE, PLANNED_DATE.plusDays(14),
                OffsetDateTime.now(ZoneOffset.UTC),
                OffsetDateTime.now(ZoneOffset.UTC),
                null, null, null,
                1L,
                List.of()
        );
    }

    private Batch plannedBatchWithDifferentRecipe() {
        return Batch.reconstitute(
                BatchId.of("batch-1"),
                new BatchNumber("P-2026-02-24-001"),
                RecipeId.of("recipe-other"),
                BatchStatus.PLANNED,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                null, null, null,
                PLANNED_DATE, PLANNED_DATE.plusDays(14),
                OffsetDateTime.now(ZoneOffset.UTC),
                OffsetDateTime.now(ZoneOffset.UTC),
                null, null, null,
                1L,
                List.of()
        );
    }

    private Batch inProductionBatch() {
        return Batch.reconstitute(
                BatchId.of("batch-1"),
                new BatchNumber("P-2026-02-24-001"),
                RecipeId.of("recipe-1"),
                BatchStatus.IN_PRODUCTION,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                null, null, null,
                PLANNED_DATE, PLANNED_DATE.plusDays(14),
                OffsetDateTime.now(ZoneOffset.UTC),
                OffsetDateTime.now(ZoneOffset.UTC),
                null, null, null,
                1L,
                List.of()
        );
    }

    @Test
    @DisplayName("should start production when order is RELEASED and batch is PLANNED")
    void should_StartProduction_When_ValidCommand() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(releasedOrder())));
        when(batchRepository.findById(BatchId.of("batch-1")))
                .thenReturn(Result.success(Optional.of(plannedBatch())));
        when(productionOrderRepository.save(any())).thenReturn(Result.success(null));
        when(batchRepository.save(any())).thenReturn(Result.success(null));

        var result = startProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isSuccess()).isTrue();
        var order = result.unsafeGetValue();
        assertThat(order.status()).isEqualTo(ProductionOrderStatus.IN_PROGRESS);
        assertThat(order.batchId()).isEqualTo(BatchId.of("batch-1"));
        verify(productionOrderRepository).save(any(ProductionOrder.class));
        verify(batchRepository).save(any(Batch.class));
    }

    @Test
    @DisplayName("should fail when actor lacks PRODUCTION_ORDER_WRITE permission")
    void should_Fail_When_Unauthorized() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(false);

        var result = startProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.Unauthorized.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when production order not found")
    void should_Fail_When_OrderNotFound() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.empty()));

        var result = startProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.ProductionOrderNotFound.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when batch not found")
    void should_Fail_When_BatchNotFound() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(releasedOrder())));
        when(batchRepository.findById(BatchId.of("batch-1")))
                .thenReturn(Result.success(Optional.empty()));

        var result = startProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.ValidationFailure.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when batch is not PLANNED")
    void should_Fail_When_BatchNotPlanned() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(releasedOrder())));
        when(batchRepository.findById(BatchId.of("batch-1")))
                .thenReturn(Result.success(Optional.of(inProductionBatch())));

        var result = startProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.ValidationFailure.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when batch recipe does not match order recipe")
    void should_Fail_When_RecipeMismatch() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(releasedOrder())));
        when(batchRepository.findById(BatchId.of("batch-1")))
                .thenReturn(Result.success(Optional.of(plannedBatchWithDifferentRecipe())));

        var result = startProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.ValidationFailure.class);
        assertThat(result.unsafeGetError().message()).contains("does not match order recipe");
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when order is not RELEASED")
    void should_Fail_When_OrderNotReleased() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(plannedOrder())));
        when(batchRepository.findById(BatchId.of("batch-1")))
                .thenReturn(Result.success(Optional.of(plannedBatch())));

        var result = startProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.InvalidStatusTransition.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when order repository returns error")
    void should_Fail_When_OrderRepositoryError() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("connection lost")));

        var result = startProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.RepositoryFailure.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when batch repository findById returns error")
    void should_Fail_When_BatchRepositoryError() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(releasedOrder())));
        when(batchRepository.findById(BatchId.of("batch-1")))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("connection lost")));

        var result = startProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.RepositoryFailure.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when order save fails")
    void should_Fail_When_OrderSaveFails() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(releasedOrder())));
        when(batchRepository.findById(BatchId.of("batch-1")))
                .thenReturn(Result.success(Optional.of(plannedBatch())));
        when(productionOrderRepository.save(any()))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("disk full")));

        var result = startProductionOrder.execute(validCommand(), performedBy);

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

    @Test
    @DisplayName("should fail when batch save fails")
    void should_Fail_When_BatchSaveFails() {
        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(releasedOrder())));
        when(batchRepository.findById(BatchId.of("batch-1")))
                .thenReturn(Result.success(Optional.of(plannedBatch())));
        when(productionOrderRepository.save(any())).thenReturn(Result.success(null));
        when(batchRepository.save(any()))
                .thenReturn(Result.failure(new RepositoryError.DatabaseError("disk full")));

        var result = startProductionOrder.execute(validCommand(), performedBy);

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

    @Test
    @DisplayName("should fail when batch is COMPLETED")
    void should_Fail_When_BatchCompleted() {
        var completedBatch = Batch.reconstitute(
                BatchId.of("batch-1"),
                new BatchNumber("P-2026-02-24-001"),
                RecipeId.of("recipe-1"),
                BatchStatus.COMPLETED,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                Quantity.of(new BigDecimal("95"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                Quantity.of(new BigDecimal("5"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                "done",
                PLANNED_DATE, PLANNED_DATE.plusDays(14),
                OffsetDateTime.now(ZoneOffset.UTC),
                OffsetDateTime.now(ZoneOffset.UTC),
                OffsetDateTime.now(ZoneOffset.UTC),
                null, null,
                1L,
                List.of()
        );

        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(releasedOrder())));
        when(batchRepository.findById(BatchId.of("batch-1")))
                .thenReturn(Result.success(Optional.of(completedBatch)));

        var result = startProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.ValidationFailure.class);
        verify(productionOrderRepository, never()).save(any());
    }

    @Test
    @DisplayName("should fail when batch is CANCELLED")
    void should_Fail_When_BatchCancelled() {
        var cancelledBatch = Batch.reconstitute(
                BatchId.of("batch-1"),
                new BatchNumber("P-2026-02-24-001"),
                RecipeId.of("recipe-1"),
                BatchStatus.CANCELLED,
                Quantity.of(new BigDecimal("100"), UnitOfMeasure.KILOGRAM).unsafeGetValue(),
                null, null, null,
                PLANNED_DATE, PLANNED_DATE.plusDays(14),
                OffsetDateTime.now(ZoneOffset.UTC),
                OffsetDateTime.now(ZoneOffset.UTC),
                null,
                "Storniert", OffsetDateTime.now(ZoneOffset.UTC),
                1L,
                List.of()
        );

        when(authPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)).thenReturn(true);
        when(productionOrderRepository.findById(ProductionOrderId.of("order-1")))
                .thenReturn(Result.success(Optional.of(releasedOrder())));
        when(batchRepository.findById(BatchId.of("batch-1")))
                .thenReturn(Result.success(Optional.of(cancelledBatch)));

        var result = startProductionOrder.execute(validCommand(), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(ProductionOrderError.ValidationFailure.class);
        verify(productionOrderRepository, never()).save(any());
    }
}
