package gc.mda.kcg.auth;

import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;

import java.time.OffsetDateTime;
import java.util.UUID;

@Entity
@Table(name = "auth_user", schema = "kcg")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {

    @Id
    @JdbcTypeCode(SqlTypes.UUID)
    @Column(name = "user_id", updatable = false, nullable = false)
    private UUID userId;

    @Column(name = "user_acnt", nullable = false, unique = true, length = 50)
    private String userAcnt;

    @Column(name = "pswd_hash", length = 255)
    private String pswdHash;

    @Column(name = "user_nm", nullable = false, length = 100)
    private String userNm;

    @Column(name = "rnkp_nm", length = 50)
    private String rnkpNm;

    @Column(name = "email", length = 255)
    private String email;

    @Column(name = "org_sn")
    private Long orgSn;

    @Column(name = "user_stts_cd", nullable = false, length = 20)
    private String userSttsCd;  // PENDING/ACTIVE/LOCKED/INACTIVE/REJECTED

    @Column(name = "fail_cnt", nullable = false)
    private Integer failCnt;

    @Column(name = "last_login_dtm")
    private OffsetDateTime lastLoginDtm;

    @Column(name = "auth_provider", nullable = false, length = 20)
    private String authProvider;  // PASSWORD/GPKI/SSO

    @Column(name = "provider_sub", length = 255)
    private String providerSub;

    @Column(name = "created_at", nullable = false)
    private OffsetDateTime createdAt;

    @Column(name = "updated_at", nullable = false)
    private OffsetDateTime updatedAt;

    @PrePersist
    void prePersist() {
        if (userId == null) userId = UUID.randomUUID();
        OffsetDateTime now = OffsetDateTime.now();
        if (createdAt == null) createdAt = now;
        if (updatedAt == null) updatedAt = now;
        if (failCnt == null) failCnt = 0;
        if (userSttsCd == null) userSttsCd = "PENDING";
        if (authProvider == null) authProvider = "PASSWORD";
    }

    @PreUpdate
    void preUpdate() {
        updatedAt = OffsetDateTime.now();
    }

    public boolean isActive() {
        return "ACTIVE".equals(userSttsCd);
    }

    public boolean isLocked() {
        return "LOCKED".equals(userSttsCd);
    }
}
