package relations.one2many;

import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * ============================================================================
 * 关系情形 ①：一对多 1:N —— 一端（Post）
 * ============================================================================
 *
 * 【关系 / Relationship】
 * EN — One post has many comments; each comment belongs to exactly one post.
 *      The foreign key lives in the COMMENT table (the "many" side), so this side is the
 *      inverse side and only needs mappedBy = "post".
 * 中 — 一篇帖子有多条评论；每条评论只属于一篇帖子。外键在评论表（“多”的一侧），
 *      所以这一端是反向端，只需 mappedBy = "post"。
 *
 * 【生成表 / Generated tables】
 *   post(id, title, body)
 *   comment(id, content, created_at, post_id)     ← 外键在这里
 *
 * 【考试判断 / Exam cue】
 * EN — "one X has many Y; each Y belongs to one X" and there is NO extra data on the
 *      relationship itself → plain 1:N, no intermediate entity.
 * 中 — “一个 X 有多个 Y，每个 Y 属于一个 X”，且关系上没有额外数据 → 普通 1:N，不需要中间实体。
 */
@Entity
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String body;

    /** 反向端：mappedBy 的值是 Comment 类里的字段名 */
    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Comment> comments = new ArrayList<>();

    public Post() { }
    public Post(String title, String body) { this.title = title; this.body = body; }

    /** 双向一致性：加评论时同时设置对方的 post 字段 */
    public void addComment(Comment comment) {
        comments.add(comment);
        comment.setPost(this);
    }

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
    public String getBody() { return body; }
    public void setBody(String body) { this.body = body; }
    public List<Comment> getComments() { return comments; }
}
