package app.mealsmadeeasy.api.recipe.star;

import app.mealsmadeeasy.api.recipe.Recipe;
import app.mealsmadeeasy.api.user.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.time.OffsetDateTime;
import java.util.Objects;

@Entity
@Table(name = "recipe_star")
@Getter
@Setter
@ToString
public final class RecipeStar {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(updatable = false)
    @JsonIgnore
    private Long id;

    @ManyToOne
    @JoinColumn(name = "owner_id", nullable = false, updatable = false)
    @JsonIgnore
    private User owner;

    @ManyToOne
    @JoinColumn(name = "recipe_id", nullable = false, updatable = false)
    @JsonIgnore
    private Recipe recipe;

    @Basic(optional = false)
    @Column(updatable = false)
    private OffsetDateTime timestamp = OffsetDateTime.now();

    @PrePersist
    public void prePersist() {
        this.timestamp = OffsetDateTime.now();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o instanceof RecipeStar other) {
            return Objects.equals(this.recipe.getOwner().getUsername(), other.getOwner().getUsername())
                    && Objects.equals(this.recipe.getSlug(), other.getRecipe().getSlug())
                    && Objects.equals(this.owner.getUsername(), other.getOwner().getUsername());
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.recipe.getOwner().getUsername(), this.recipe.getSlug(), this.owner.getUsername());
    }

}
