package de.effigenix.application.usermanagement;

import de.effigenix.application.usermanagement.command.LockUserCommand;
import de.effigenix.application.usermanagement.dto.UserDTO;
import de.effigenix.domain.usermanagement.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.security.ActorId;
import de.effigenix.shared.persistence.UnitOfWork;
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.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.Optional;
import java.util.function.Supplier;

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

@ExtendWith(MockitoExtension.class)
@DisplayName("LockUser Use Case")
class LockUserTest {

    @Mock private UserRepository userRepository;
    @Mock private AuditLogger auditLogger;
    @Mock private AuthorizationPort authPort;
    @Mock private UnitOfWork unitOfWork;

    private LockUser lockUser;
    private ActorId performedBy;
    private User activeUser;

    @BeforeEach
    void setUp() {
        lenient().when(unitOfWork.executeAtomically(any()))
                .thenAnswer(inv -> ((Supplier<?>) inv.getArgument(0)).get());
        lockUser = new LockUser(userRepository, auditLogger, authPort, unitOfWork);
        performedBy = ActorId.of("admin-user");
        activeUser = User.reconstitute(
                UserId.of("user-1"), "john.doe", "john@example.com",
                new PasswordHash("$2a$12$R9h/cIPz0gi.URNN3kh2OPST9EBwVeL00lzQRYe3z08MZx3e8YCWW"),
                new HashSet<>(), "branch-1", UserStatus.ACTIVE, OffsetDateTime.now(ZoneOffset.UTC), null
        );
    }

    @Test
    @DisplayName("should_LockUser_When_UserIsActive")
    void should_LockUser_When_UserIsActive() {
        when(authPort.can(performedBy, UserManagementAction.USER_LOCK)).thenReturn(true);
        when(userRepository.findById(UserId.of("user-1"))).thenReturn(Result.success(Optional.of(activeUser)));
        when(userRepository.save(any())).thenReturn(Result.success(null));

        Result<UserError, UserDTO> result = lockUser.execute(new LockUserCommand("user-1"), performedBy);

        assertThat(result.isSuccess()).isTrue();
        assertThat(result.unsafeGetValue().status()).isEqualTo(UserStatus.LOCKED);
        verify(userRepository).save(argThat(user -> user.status() == UserStatus.LOCKED));
        verify(auditLogger).log(eq(AuditEvent.USER_LOCKED), eq("user-1"), eq(performedBy));
    }

    @Test
    @DisplayName("should_FailWithUnauthorized_When_ActorLacksPermission")
    void should_FailWithUnauthorized_When_ActorLacksPermission() {
        when(authPort.can(performedBy, UserManagementAction.USER_LOCK)).thenReturn(false);

        Result<UserError, UserDTO> result = lockUser.execute(new LockUserCommand("user-1"), performedBy);

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

    @Test
    @DisplayName("should_FailWithInvalidInput_When_UserIdIsBlank")
    void should_FailWithInvalidInput_When_UserIdIsBlank() {
        when(authPort.can(performedBy, UserManagementAction.USER_LOCK)).thenReturn(true);

        Result<UserError, UserDTO> result = lockUser.execute(new LockUserCommand(""), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(UserError.InvalidInput.class);
    }

    @Test
    @DisplayName("should_FailWithUserNotFound_When_UserDoesNotExist")
    void should_FailWithUserNotFound_When_UserDoesNotExist() {
        when(authPort.can(performedBy, UserManagementAction.USER_LOCK)).thenReturn(true);
        when(userRepository.findById(UserId.of("nonexistent"))).thenReturn(Result.success(Optional.empty()));

        Result<UserError, UserDTO> result = lockUser.execute(new LockUserCommand("nonexistent"), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(UserError.UserNotFound.class);
    }

    @Test
    @DisplayName("should_FailWithInvalidStatusTransition_When_UserAlreadyLocked")
    void should_FailWithInvalidStatusTransition_When_UserAlreadyLocked() {
        User lockedUser = User.reconstitute(
                UserId.of("user-2"), "jane.doe", "jane@example.com",
                new PasswordHash("$2a$12$R9h/cIPz0gi.URNN3kh2OPST9EBwVeL00lzQRYe3z08MZx3e8YCWW"),
                new HashSet<>(), "branch-1", UserStatus.LOCKED, OffsetDateTime.now(ZoneOffset.UTC), null
        );
        when(authPort.can(performedBy, UserManagementAction.USER_LOCK)).thenReturn(true);
        when(userRepository.findById(UserId.of("user-2"))).thenReturn(Result.success(Optional.of(lockedUser)));

        Result<UserError, UserDTO> result = lockUser.execute(new LockUserCommand("user-2"), performedBy);

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

    @Test
    @DisplayName("should_FailWithInvalidStatusTransition_When_UserIsInactive")
    void should_FailWithInvalidStatusTransition_When_UserIsInactive() {
        User inactiveUser = User.reconstitute(
                UserId.of("user-3"), "bob", "bob@example.com",
                new PasswordHash("$2a$12$R9h/cIPz0gi.URNN3kh2OPST9EBwVeL00lzQRYe3z08MZx3e8YCWW"),
                new HashSet<>(), "branch-1", UserStatus.INACTIVE, OffsetDateTime.now(ZoneOffset.UTC), null
        );
        when(authPort.can(performedBy, UserManagementAction.USER_LOCK)).thenReturn(true);
        when(userRepository.findById(UserId.of("user-3"))).thenReturn(Result.success(Optional.of(inactiveUser)));

        Result<UserError, UserDTO> result = lockUser.execute(new LockUserCommand("user-3"), performedBy);

        assertThat(result.isFailure()).isTrue();
        assertThat(result.unsafeGetError()).isInstanceOf(UserError.InvalidStatusTransition.class);
    }
}
