package com.gcsc.connection.user.entity;

import com.gcsc.connection.common.entity.BaseEntity;
import com.gcsc.connection.tenant.entity.SnpTenant;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Getter
@NoArgsConstructor(access = lombok.AccessLevel.PROTECTED)
@Entity
@Table(name = "snp_user", schema = "common")
public class SnpUser extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Long userId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tenant_id")
    private SnpTenant tenant;

    @Column(name = "login_id", length = 100, nullable = false, unique = true)
    private String loginId;

    @Column(name = "password_hash", length = 255, nullable = false)
    private String passwordHash;

    @Column(name = "user_name", length = 100, nullable = false)
    private String userName;

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

    @Enumerated(EnumType.STRING)
    @Column(name = "role", length = 20, nullable = false)
    private UserRole role = UserRole.USER;

    @Column(name = "is_active", nullable = false)
    private Boolean isActive = true;

    @Column(name = "last_login_at")
    private LocalDateTime lastLoginAt;

    @Builder
    public SnpUser(SnpTenant tenant, String loginId, String passwordHash, String userName,
                   String email, UserRole role, Boolean isActive) {
        this.tenant = tenant;
        this.loginId = loginId;
        this.passwordHash = passwordHash;
        this.userName = userName;
        this.email = email;
        this.role = role != null ? role : UserRole.USER;
        this.isActive = isActive != null ? isActive : true;
    }

    public void updateLastLoginAt() {
        this.lastLoginAt = LocalDateTime.now();
    }

    public void update(SnpTenant tenant, String userName, String email, UserRole role, Boolean isActive) {
        if (tenant != null) this.tenant = tenant;
        if (userName != null) this.userName = userName;
        if (email != null) this.email = email;
        if (role != null) this.role = role;
        if (isActive != null) this.isActive = isActive;
    }

    public void updatePassword(String passwordHash) {
        this.passwordHash = passwordHash;
    }

    public void deactivate() {
        this.isActive = false;
    }
}
