package com.home4j.entity;

import io.quarkus.elytron.security.common.BcryptUtil;
import io.quarkus.hibernate.orm.panache.PanacheEntity;
import io.quarkus.security.jpa.Password;
import io.quarkus.security.jpa.PasswordType;
import io.quarkus.security.jpa.Roles;
import io.quarkus.security.jpa.UserDefinition;
import io.quarkus.security.jpa.Username;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

import java.time.LocalDateTime;

/**
 * 用户实体 - 管理员账户
 */
@Entity
@Table(name = "t_user")
@UserDefinition
public class User extends PanacheEntity {

    /**
     * 用户名（唯一）
     */
    @Username
    @NotBlank(message = "用户名不能为空")
    @Size(min = 3, max = 50, message = "用户名长度必须在3-50之间")
    @Column(nullable = false, unique = true, length = 50)
    public String username;

    /**
     * 密码（MCF格式，使用BCrypt）
     */
    @Password(value = PasswordType.MCF)
    @NotBlank(message = "密码不能为空")
    @Column(nullable = false, length = 100)
    public String password;

    /**
     * 角色（ADMIN）
     */
    @Roles
    @Column(nullable = false, length = 20)
    public String role = "ADMIN";

    /**
     * 创建时间
     */
    @Column(name = "created_at", nullable = false, updatable = false)
    public LocalDateTime createdAt;

    /**
     * 更新时间
     */
    @Column(name = "updated_at")
    public LocalDateTime updatedAt;

    @PrePersist
    public void prePersist() {
        this.createdAt = LocalDateTime.now();
        this.updatedAt = LocalDateTime.now();
    }

    @PreUpdate
    public void preUpdate() {
        this.updatedAt = LocalDateTime.now();
    }

    /**
     * 根据用户名查找用户
     */
    public static User findByUsername(String username) {
        return find("username", username).firstResult();
    }
}
