package de.effigenix.application.usermanagement;

import de.effigenix.application.usermanagement.dto.UserDTO;
import de.effigenix.domain.usermanagement.UserError;
import de.effigenix.domain.usermanagement.UserManagementAction;
import de.effigenix.domain.usermanagement.UserRepository;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.security.ActorId;
import de.effigenix.shared.security.AuthorizationPort;
import de.effigenix.shared.security.BranchId;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Use Case: List all users (with optional branch filtering).
 */
public class ListUsers {

    private final UserRepository userRepository;
    private final AuthorizationPort authPort;

    public ListUsers(UserRepository userRepository, AuthorizationPort authPort) {
        this.userRepository = userRepository;
        this.authPort = authPort;
    }

    /**
     * Lists all users (admin view).
     */
    public Result<UserError, List<UserDTO>> execute(ActorId performedBy) {
        if (!authPort.can(performedBy, UserManagementAction.USER_LIST)) {
            return Result.failure(new UserError.Unauthorized("Not authorized to list users"));
        }

        return userRepository.findAll()
                .mapError(err -> (UserError) new UserError.RepositoryFailure(err.message()))
                .map(users -> users.stream().map(UserDTO::from).collect(Collectors.toList()));
    }

    /**
     * Lists users for a specific branch (filtered view).
     */
    public Result<UserError, List<UserDTO>> executeForBranch(BranchId branchId, ActorId performedBy) {
        if (!authPort.can(performedBy, UserManagementAction.USER_LIST)) {
            return Result.failure(new UserError.Unauthorized("Not authorized to list users"));
        }

        return userRepository.findByBranchId(branchId.value())
                .mapError(err -> (UserError) new UserError.RepositoryFailure(err.message()))
                .map(users -> users.stream().map(UserDTO::from).collect(Collectors.toList()));
    }
}
