package app.mealsmadeeasy.api.recipe.star;

import app.mealsmadeeasy.api.PostgresTestsExtension;
import app.mealsmadeeasy.api.recipe.Recipe;
import app.mealsmadeeasy.api.recipe.RecipeRepository;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.time.OffsetDateTime;
import java.util.UUID;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

@SpringBootTest
@ExtendWith(PostgresTestsExtension.class)
public class RecipeStarRepositoryTests {

    @Autowired
    private RecipeStarRepository recipeStarRepository;

    @Autowired
    private RecipeRepository recipeRepository;

    @Autowired
    private UserRepository userRepository;

    private User seedUser() {
        final User draft = User.getDefaultDraft();
        final String uuid = UUID.randomUUID().toString();
        draft.setUsername(uuid);
        draft.setEmail(uuid + "@test.com");
        draft.setPassword("test");
        return this.userRepository.save(draft);
    }

    private Recipe getTestRecipe(User owner) {
        final Recipe recipeDraft = new Recipe();
        recipeDraft.setCreated(OffsetDateTime.now());
        recipeDraft.setSlug(UUID.randomUUID().toString());
        recipeDraft.setOwner(owner);
        recipeDraft.setTitle("Test Recipe");
        recipeDraft.setRawText("Hello, World!");
        return this.recipeRepository.save(recipeDraft);
    }

    @Test
    public void returnsTrueIfStarer() {
        final User owner = this.seedUser();
        final Recipe recipe = this.getTestRecipe(owner);

        final RecipeStar starDraft = new RecipeStar();
        starDraft.setRecipe(recipe);
        starDraft.setOwner(owner);
        this.recipeStarRepository.save(starDraft);

        assertThat(
                this.recipeStarRepository.isStarer(
                        recipe.getOwner().getUsername(),
                        recipe.getSlug(),
                        owner.getId()
                ),
                is(true)
        );
    }

    @Test
    public void returnsFalseIfNotStarer() {
        final User owner = this.seedUser();
        final Recipe recipe = this.getTestRecipe(owner);
        assertThat(
                this.recipeStarRepository.isStarer(
                        recipe.getOwner().getUsername(),
                        recipe.getSlug(),
                        owner.getId()
                ),
                is(false)
        );
    }

}
