package com.pingcap.community.blogserver.entity;

import com.fasterxml.jackson.annotation.JsonView;
import com.pingcap.community.blogserver.enums.NotificationType;
import lombok.*;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;

import javax.persistence.*;

@Entity(name = "notification")
@Table(name = "notifications")
@SQLDelete(sql = "UPDATE notifications SET deleted_at = now() WHERE id = ?")
@Where(clause = "deleted_at is null")
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Notification extends BaseEntity {

  public interface NotificationItemView extends Post.PostTitleView, User.UserLoginView, Comment.CommentSimpleView, BaseEntity.TimeInfoView {}

  public Notification(Long id) {
    this.id = id;
  }

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id", nullable = false)
  @JsonView(NotificationItemView.class)
  private Long id;

  @Enumerated(EnumType.STRING)
  @Column(name = "type", nullable = false, length = 20)
  @JsonView(NotificationItemView.class)
  private NotificationType type;

  @JsonView(NotificationItemView.class)
  private String title;

  @Lob
  @Basic(fetch = FetchType.LAZY)
  @ToString.Exclude
  private String content;

  @Column(name = "have_read", nullable = false, columnDefinition = "bit(1) default 0")
  @JsonView(NotificationItemView.class)
  private Boolean haveRead;

  @Column(name = "target_url")
  @JsonView(NotificationItemView.class)
  private String target_url;

  @ManyToOne
  @JsonView(NotificationItemView.class)
  @JoinColumn(name = "recipient_id")
  private User recipient;

  @ManyToOne(fetch = FetchType.LAZY)
  @NotFound(action = NotFoundAction.IGNORE)
  @JsonView(NotificationItemView.class)
  @JoinColumn(name = "actor_id")
  @ToString.Exclude
  private User actor;

  @ManyToOne(fetch = FetchType.LAZY)
  @NotFound(action = NotFoundAction.IGNORE)
  @JsonView(NotificationItemView.class)
  @JoinColumn(name = "related_post_id")
  @ToString.Exclude
  private Post relatedPost;

  @ManyToOne(fetch = FetchType.LAZY)
  @NotFound(action = NotFoundAction.IGNORE)
  @JsonView(NotificationItemView.class)
  @JoinColumn(name = "related_comment_id")
  @ToString.Exclude
  private Comment relatedComment;

  public void setTitle(String title, Object... args) {
    this.title = String.format(title, args);
  }

}
