package app.mealsmadeeasy.api.image.converter;

import app.mealsmadeeasy.api.image.body.ImageUpdateBody;
import app.mealsmadeeasy.api.image.spec.ImageUpdateSpec;
import app.mealsmadeeasy.api.user.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class ImageUpdateBodyToSpecConverter {

    private final UserService userService;

    public ImageUpdateSpec convert(ImageUpdateBody body) {
        final var builder = ImageUpdateSpec.builder()
                .alt(body.getAlt())
                .caption(body.getCaption())
                .isPublic(body.getIsPublic())
                .clearAllViewers(body.getClearAllViewers());
        if (body.getViewersToAdd() != null) {
            builder.viewersToAdd(body.getViewersToAdd().stream()
                    .map(this.userService::getUser)
                    .collect(Collectors.toSet())
            );
        }
        if (body.getViewersToRemove() != null) {
            builder.viewersToRemove(body.getViewersToRemove().stream()
                    .map(this.userService::getUser)
                    .collect(Collectors.toSet())
            );
        }
        return builder.build();
    }

}
