package com.kamco.cd.training.postgres.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.time.ZonedDateTime;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

@Getter
@Setter
@Entity
@Table(name = "auth_refresh_token")
@NoArgsConstructor
public class AuthRefreshTokenEntity {

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

  @Size(max = 255)
  @NotNull
  @Column(name = "subject", nullable = false)
  private String subject;

  @NotNull
  @Column(name = "token", nullable = false, length = Integer.MAX_VALUE)
  private String token;

  @NotNull
  @Column(name = "expires_dttm", nullable = false)
  private ZonedDateTime expiresDttm;

  @Column(name = "revoked_dttm")
  private ZonedDateTime revokedDttm;

  @CreationTimestamp
  @Column(updatable = false)
  private ZonedDateTime createdDttm;

  @UpdateTimestamp private ZonedDateTime updatedDttm;

  public AuthRefreshTokenEntity(String subject, String token, ZonedDateTime expiresDttm) {
    this.subject = subject;
    this.token = token;
    this.expiresDttm = expiresDttm;
  }

  public void rotate(String token, ZonedDateTime expiresDttm) {
    this.token = token;
    this.expiresDttm = expiresDttm;
    this.revokedDttm = null;
  }

  public void revoke() {
    this.revokedDttm = ZonedDateTime.now();
  }
}
