package com.agent.management.model.entity;

import jakarta.persistence.*;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * 知识库文档元数据
 *
 * <p>状态机：
 * <pre>
 * PENDING → PARSING → CHUNKING → EMBEDDING → VECTORIZING → READY
 *                                              └→ FAILED
 * </pre>
 * 任一步失败置为 FAILED，errorMessage 记录原因。</p>
 */
@Data
@Entity
@Table(name = "kb_document")
public class KbDocument {

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

    @Column(nullable = false)
    private String name;

    /**
     * 所属分类 ID（null 表示未分类）
     */
    @Column(name = "category_id")
    private Long categoryId;

    /**
     * 原始文件相对路径（相对 app.kb.upload-dir）
     */
    @Column(name = "source_path", nullable = false)
    private String sourcePath;

    @Column(name = "file_size")
    private Long fileSize;

    @Column(name = "mime_type")
    private String mimeType;

    /**
     * 处理状态：PENDING/PARSING/CHUNKING/EMBEDDING/VECTORIZING/READY/FAILED
     */
    @Column(nullable = false)
    private String status = "PENDING";

    @Column(name = "chunk_count")
    private Integer chunkCount = 0;

    @Column(name = "vector_count")
    private Integer vectorCount = 0;

    // 长度 1000：与 DocumentPipelineImpl 中 errorMessage 截断上限对齐，
    // 255 字符对错误堆栈摘要过短，无法定位问题。
    @Column(name = "error_message", length = 1000)
    private String errorMessage;

    @Column(name = "created_at")
    private LocalDateTime createdAt;

    @Column(name = "updated_at")
    private LocalDateTime updatedAt;

    @PrePersist
    protected void onCreate() {
        LocalDateTime now = LocalDateTime.now();
        if (createdAt == null) createdAt = now;
        updatedAt = now;
    }

    @PreUpdate
    protected void onUpdate() {
        updatedAt = LocalDateTime.now();
    }
}
