package de.thpeetz.kontor.comics.data;

import java.util.LinkedList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import de.thpeetz.kontor.common.data.AbstractEntity;
import jakarta.annotation.Nullable;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.Column;
import jakarta.persistence.OneToMany;
import jakarta.persistence.ManyToOne;
import jakarta.validation.constraints.*;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
@Entity
public class Publisher extends AbstractEntity {

    @NotEmpty
    @Column(unique = true)
    private String name;

    private String weblink;

    @JsonBackReference
    @ManyToOne
    @JoinColumn(name = "parent_publisher_id")
    @Nullable
    @JsonIgnoreProperties({ "comics" })
    private Publisher parentCompany;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parentCompany", cascade = CascadeType.ALL, orphanRemoval = true)
    @Nullable
    private List<Publisher> imprints = new LinkedList<>();

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "publisher", cascade = CascadeType.ALL, orphanRemoval = true)
    @Nullable
    private List<Comic> comics = new LinkedList<>();

    public String getParentCompanyName() {
        if (parentCompany != null) {
            return parentCompany.name;
        }
        return null;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Publisher{");
        sb.append("name='").append(name).append('\'');
        sb.append('}');
        return sb.toString();
    }
}
