package com.its.op.entity.its;

import lombok.Getter;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Getter
@MappedSuperclass   // JPA Entity 클래스들이 AuditingEntity 를 상속할 경우 필드들(createdDate, lastModifiedDate)도 칼럼으로 인식하도록 함
@EntityListeners(AuditingEntityListener.class)  // AuditingEntity 클래스에 Auditing 기능을 포함
public class AuditingEntity {

    @CreatedDate
    @Column(updatable = false)
    private LocalDateTime createdTime;

    // AuditorAwareConfig
    // @Bean
    // public AuditorAware<String> auditorProvider()
    @CreatedBy
    @Column(updatable = false)
    private String createdBy;

    @LastModifiedDate
    private LocalDateTime modifiedTime;

    @LastModifiedBy
    private String modifiedBy;

    // 생성
    @PrePersist
    public void onPrePersist() {
        LocalDateTime now = LocalDateTime.now();
        String createDt = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        this.createdTime = now;
        this.modifiedTime = now;
    }

    // 업데이트
    @PreUpdate
    public void onPreUpdate() {
        LocalDateTime now = LocalDateTime.now();
        String updateDt = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        this.modifiedTime = now;
    }
}

//// JPA Auditing 클래스 상속
//public class MyEntiry extends AuditingEntity {
//}
//
//@EnableJpaAuditing    // JPA Auditing 활성화
//@SpringBootApplication
//public class Application {
//    public static void main(String[] args) {
//        SpringApplication.run(Application.class, args);
//    }
//}
//
