package de.effigenix.infrastructure.usermanagement.persistence.mapper;

import de.effigenix.domain.usermanagement.Role;
import de.effigenix.domain.usermanagement.RoleId;
import de.effigenix.infrastructure.usermanagement.persistence.entity.RoleEntity;
import org.springframework.stereotype.Component;

import java.util.HashSet;

/**
 * Maps between Role domain entity and RoleEntity JPA entity.
 * Infrastructure Layer - translates between Domain and Persistence layers.
 *
 * This is a crucial part of Hexagonal Architecture:
 * - Domain layer defines pure business logic (Role)
 * - Infrastructure layer handles persistence (RoleEntity)
 * - Mapper translates between the two layers
 */
@Component
public class RoleMapper {

    /**
     * Converts a Role domain entity to a RoleEntity JPA entity.
     * Used when saving to the database.
     */
    public RoleEntity toEntity(Role role) {
        if (role == null) {
            return null;
        }

        return new RoleEntity(
                role.id().value(),
                role.name(),
                new HashSet<>(role.permissions()),
                role.description()
        );
    }

    /**
     * Converts a RoleEntity JPA entity to a Role domain entity.
     * Used when loading from the database.
     */
    public Role toDomain(RoleEntity entity) {
        if (entity == null) {
            return null;
        }

        return Role.reconstitute(
                RoleId.of(entity.getId()),
                entity.getName(),
                new HashSet<>(entity.getPermissions()),
                entity.getDescription()
        );
    }
}
