package app.mealsmadeeasy.api.recipe;

import app.mealsmadeeasy.api.user.User;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.UUID;

@Component
@RequiredArgsConstructor
public class RecipeDraftSecurity {

    private final RecipeDraftRepository recipeDraftRepository;

    public boolean isViewableBy(RecipeDraft recipeDraft, @Nullable User viewer) {
        if (viewer == null) {
            return false;
        }
        return recipeDraft.getOwner().getId().equals(viewer.getId());
    }

    public boolean isUpdatableBy(UUID id, @Nullable User modifier) {
        if (modifier == null) {
            return false;
        }
        final Optional<RecipeDraft> maybeTarget = this.recipeDraftRepository.findById(id);
        if (maybeTarget.isEmpty()) {
            return false;
        }
        final RecipeDraft target = maybeTarget.get();
        return target.getOwner().getId().equals(modifier.getId());
    }

}
