package de.effigenix.application.usermanagement;

import de.effigenix.application.usermanagement.command.RemoveRoleCommand;
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.Set;
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("RemoveRole Use Case")
class RemoveRoleTest {

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

    private RemoveRole removeRole;
    private ActorId performedBy;
    private Role workerRole;
    private User userWithRole;

    @BeforeEach
    void setUp() {
        lenient().when(unitOfWork.executeAtomically(any()))
                .thenAnswer(inv -> ((Supplier<?>) inv.getArgument(0)).get());
        removeRole = new RemoveRole(userRepository, roleRepository, auditLogger, authPort, unitOfWork);
        performedBy = ActorId.of("admin-user");
        workerRole = Role.reconstitute(RoleId.generate(), RoleName.PRODUCTION_WORKER, new HashSet<>(), "Production Worker");
        userWithRole = User.reconstitute(
                UserId.of("user-1"), "john.doe", "john@example.com",
                new PasswordHash("$2a$12$R9h/cIPz0gi.URNN3kh2OPST9EBwVeL00lzQRYe3z08MZx3e8YCWW"),
                new HashSet<>(Set.of(workerRole)), "branch-1", UserStatus.ACTIVE, OffsetDateTime.now(ZoneOffset.UTC), null
        );
    }

    @Test
    @DisplayName("should_RemoveRole_When_ValidCommandProvided")
    void should_RemoveRole_When_ValidCommandProvided() {
        when(authPort.can(performedBy, UserManagementAction.ROLE_REMOVE)).thenReturn(true);
        when(userRepository.findById(UserId.of("user-1"))).thenReturn(Result.success(Optional.of(userWithRole)));
        when(roleRepository.findByName(RoleName.PRODUCTION_WORKER)).thenReturn(Result.success(Optional.of(workerRole)));
        when(userRepository.save(any())).thenReturn(Result.success(null));

        Result<UserError, UserDTO> result = removeRole.execute(
                new RemoveRoleCommand("user-1", RoleName.PRODUCTION_WORKER), performedBy);

        assertThat(result.isSuccess()).isTrue();
        assertThat(result.unsafeGetValue().roles()).isEmpty();
        verify(userRepository).save(argThat(user -> user.roles().isEmpty()));
        verify(auditLogger).log(eq(AuditEvent.ROLE_REMOVED), eq("user-1"), anyString(), eq(performedBy));
    }

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

        Result<UserError, UserDTO> result = removeRole.execute(
                new RemoveRoleCommand("user-1", RoleName.PRODUCTION_WORKER), 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.ROLE_REMOVE)).thenReturn(true);

        Result<UserError, UserDTO> result = removeRole.execute(
                new RemoveRoleCommand("", RoleName.PRODUCTION_WORKER), performedBy);

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

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

        Result<UserError, UserDTO> result = removeRole.execute(
                new RemoveRoleCommand("user-1", null), 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.ROLE_REMOVE)).thenReturn(true);
        when(userRepository.findById(UserId.of("nonexistent"))).thenReturn(Result.success(Optional.empty()));

        Result<UserError, UserDTO> result = removeRole.execute(
                new RemoveRoleCommand("nonexistent", RoleName.PRODUCTION_WORKER), performedBy);

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

    @Test
    @DisplayName("should_FailWithRoleNotFound_When_RoleDoesNotExist")
    void should_FailWithRoleNotFound_When_RoleDoesNotExist() {
        when(authPort.can(performedBy, UserManagementAction.ROLE_REMOVE)).thenReturn(true);
        when(userRepository.findById(UserId.of("user-1"))).thenReturn(Result.success(Optional.of(userWithRole)));
        when(roleRepository.findByName(RoleName.ADMIN)).thenReturn(Result.success(Optional.empty()));

        Result<UserError, UserDTO> result = removeRole.execute(
                new RemoveRoleCommand("user-1", RoleName.ADMIN), performedBy);

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