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;

/**
 * 系统配置实体
 */
@Entity
@Table(name = "t_config")
public class Config extends PanacheEntity {

    /**
     * 配置键（唯一）
     */
    @NotBlank(message = "配置键不能为空")
    @Size(max = 100, message = "配置键长度不能超过100")
    @Column(name = "config_key", nullable = false, unique = true, length = 100)
    public String configKey;

    /**
     * 配置值
     */
    @Column(name = "config_value", columnDefinition = "TEXT")
    public String configValue;

    /**
     * 配置描述
     */
    @Size(max = 200, message = "描述长度不能超过200")
    @Column(length = 200)
    public String description;

    /**
     * 创建时间
     */
    @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 Config findByKey(String key) {
        return find("configKey", key).firstResult();
    }

    /**
     * 获取配置值，如果不存在返回默认值
     */
    public static String getValue(String key, String defaultValue) {
        Config config = findByKey(key);
        return config != null && config.configValue != null ? config.configValue : defaultValue;
    }

    /**
     * 设置配置值
     */
    public static void setValue(String key, String value, String description) {
        Config config = findByKey(key);
        if (config == null) {
            config = new Config();
            config.configKey = key;
            config.description = description;
        }
        config.configValue = value;
        config.persist();
    }

    // 常用配置键常量
    public static final String KEY_SITE_TITLE = "site_title";
    public static final String KEY_SITE_SUBTITLE = "site_subtitle";
    public static final String KEY_THEME = "theme";
    public static final String KEY_FOOTER_TEXT = "footer_text";
    public static final String KEY_SEARCH_ENGINE = "search_engine";
    public static final String KEY_SHOW_SEARCH = "show_search";
    public static final String KEY_VIEW_MODE = "view_mode";
    public static final String KEY_COLUMNS = "columns";
    public static final String KEY_BACKGROUND_IMAGE = "background_image";
    public static final String KEY_BACKGROUND_OVERLAY = "background_overlay";
}
