package cn.lihongjie.coal.base.entity;

import cn.lihongjie.coal.common.Ctx;

import io.hypersistence.utils.hibernate.type.array.ListArrayType;

import jakarta.persistence.*;

import lombok.Getter;
import lombok.Setter;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.*;

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

@MappedSuperclass
@Getter
@Setter
@DynamicUpdate
public class BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    private String id;

    @Comment("创建用户ID")
    @Column(updatable = false)
    private String createUserId;

    @Formula("(select tu.name from t_user tu where tu.id = create_user_id)")
    private String createUserName;

    @Comment("创建时间")
    @CreationTimestamp(source = SourceType.VM)
    @Column(updatable = false)
    private LocalDateTime createTime;

    @Comment("更新用户ID")
    private String updateUserId;

    @Formula("((select tu.name from t_user tu where tu.id = create_user_id))")
    private String updateUserName;

    @Comment("更新时间")
    @UpdateTimestamp(source = SourceType.VM)
    private LocalDateTime updateTime;

    @Comment("关联附件")
    @Column(columnDefinition = "text[]")
    @Type(ListArrayType.class)
    private List<String> fileIds;

    @PrePersist
    public void prePersist() {

        if (StringUtils.isEmpty(this.createUserId)) {

            this.createUserId = Ctx.isLoggedIn() ? Ctx.getUserId() : "";
        }

        if (this.createTime == null) {
            this.createTime = LocalDateTime.now();
        }
    }

    @PreUpdate
    public void preUpdate() {

        this.updateUserId = Ctx.isLoggedIn() ? Ctx.getUserId() : "";

        this.updateTime = LocalDateTime.now();
    }
}
