package kr.co.accura.wbx.spring.auth;

import jakarta.persistence.*;
import kr.co.accura.wbx.spring.common.BaseEntity;
import lombok.*;

import java.time.LocalDateTime;

@Entity
@Table(name = "wbx_users")
@Getter @Setter
@NoArgsConstructor @AllArgsConstructor @Builder
public class WbxUser extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false, unique = true, length = 100)
    private String username;

    private String hashedPassword;
    private String fullName;
    private String phone;

    @Column(name = "department_id")
    private Long departmentId;

    @Column(length = 100)
    private String positionTitle;

    @Column(unique = true, length = 50)
    private String employeeNumber;

    @Builder.Default
    private boolean isActive = true;

    @Builder.Default
    private boolean isAdmin = false;

    @Builder.Default
    private boolean mfaEnabled = false;

    @Column(length = 255)
    private String azureOid;

    @Column(length = 50)
    private String ssoProvider;

    @Builder.Default
    private int failedLoginAttempts = 0;

    private LocalDateTime lastFailedLogin;
    private LocalDateTime lockedUntil;
    private LocalDateTime passwordChangedAt;

    @Builder.Default
    private boolean mustChangePassword = false;

    private LocalDateTime lastLoginAt;

    // 비즈니스 메서드
    public void recordLoginSuccess() {
        this.lastLoginAt = LocalDateTime.now();
        this.failedLoginAttempts = 0;
        this.lastFailedLogin = null;
    }

    public void recordLoginFailure(int maxAttempts, int lockoutMinutes) {
        this.failedLoginAttempts++;
        this.lastFailedLogin = LocalDateTime.now();
        if (this.failedLoginAttempts >= maxAttempts) {
            this.lockedUntil = LocalDateTime.now().plusMinutes(lockoutMinutes);
        }
    }

    public boolean isLocked() {
        return lockedUntil != null && lockedUntil.isAfter(LocalDateTime.now());
    }

    public WbxUserDetails toUserDetails() {
        return WbxUserDetails.builder()
                .id(id)
                .email(email)
                .username(username)
                .fullName(fullName != null ? fullName : "")
                .isAdmin(isAdmin)
                .departmentId(departmentId)
                .build();
    }
}
