package com.codenetworkz.blog.models;

import com.codenetworkz.blog.config.SlugGenerator;
import jakarta.persistence.*;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDateTime;
import java.util.List;


@Getter
@Setter
@Entity
public class Post extends BaseModel {


    @Size(min =10, max = 255, message = "Name should be more then 10 and less then 255 character required.")
    private String name;

    @Column(unique = true)
    private String slug;

    @Lob
    private String content;

    private int likes;

    private String featuredImageUrl;

    @Column(length = 1, nullable = false)
    private Status isPublished;

    @ManyToMany
    @JoinTable(name = "posts_categories", joinColumns = @JoinColumn(name = "post_id") , inverseJoinColumns = @JoinColumn(name = "category_id"))
    private List<Category> categories;
    @ManyToMany
    @JoinTable(name = "posts_tags", joinColumns = @JoinColumn(name = "post_id") , inverseJoinColumns = @JoinColumn(name = "tag_id"))
    private List<Tag> tags;
    @ManyToMany
    @JoinTable(name = "posts_comments", joinColumns = @JoinColumn(name = "post_id") , inverseJoinColumns = @JoinColumn(name = "comment_id"))
    private List<Comment> comments;


    @PrePersist
    protected void onCreate() {
        if (super.getCreateAt() == null) {
            setCreateAt(LocalDateTime.now());
        }
        if (super.getIsDelete() == null) {
            setIsDelete(Status.NO);
        }
        if (super.getIsActive() == null) {
            setIsActive(Status.YES);
        }

        String newSlug = SlugGenerator.generateSlug(name);

        if (name != null || slug == null) {
            slug = newSlug;
        }
        if (!slug.equals(newSlug)) {
            slug = newSlug;
        }
    }

}