package com.home4j.entity;

import io.quarkus.hibernate.orm.panache.PanacheEntity;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 书签分组实体
 */
@Entity
@Table(name = "t_group")
public class BookmarkGroup extends PanacheEntity {

    /**
     * 分组名称
     */
    @NotBlank(message = "分组名称不能为空")
    @Size(max = 100, message = "分组名称长度不能超过100")
    @Column(nullable = false, length = 100)
    public String name;

    /**
     * 分组图标（Lucide图标名称）
     */
    @Size(max = 50, message = "图标名称长度不能超过50")
    @Column(length = 50)
    public String icon;

    /**
     * 排序顺序
     */
    @Column(name = "sort_order", nullable = false)
    public Integer sortOrder = 0;

    /**
     * 是否可见
     */
    @Column(nullable = false)
    public Boolean visible = true;

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

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

    /**
     * 关联的书签列表（级联删除）
     */
    @OneToMany(mappedBy = "group", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    public List<Bookmark> bookmarks;

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

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

    /**
     * 查找所有可见分组，按排序顺序
     */
    public static List<BookmarkGroup> findAllVisibleOrdered() {
        return find("visible = true ORDER BY sortOrder ASC").list();
    }

    /**
     * 查找所有分组，按排序顺序
     */
    public static List<BookmarkGroup> findAllOrdered() {
        return find("ORDER BY sortOrder ASC").list();
    }

    /**
     * 获取下一个排序序号
     */
    public static int getNextSortOrder() {
        BookmarkGroup last = find("ORDER BY sortOrder DESC").firstResult();
        return last == null ? 0 : last.sortOrder + 1;
    }
}
