package com.agent.management.model.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.PrePersist;
import jakarta.persistence.Table;
import lombok.Data;

import java.time.LocalDateTime;

/**
 * Agent 对话消息主表。
 *
 * <p>对应设计文档 {@code docs/design/agent-chat-page-design.md} §4.1.2。
 * 通过 {@code parentId + isActive + branchOrder} 形成 ChatGPT 风格的消息树，
 * 原生支持"重新生成"与"消息编辑"两个分支场景。</p>
 *
 * <p>消息文本（user 原文 / assistant 最终回复）存放在本表 {@link #content}；
 * assistant 消息的思考过程日志按"行"结构化存放到 {@code chat_message_log} 子表。</p>
 */
@Data
@Entity
@Table(name = "chat_message", indexes = {
        @Index(name = "idx_chat_message_session", columnList = "session_id, created_at"),
        @Index(name = "idx_chat_message_parent", columnList = "parent_id, is_active"),
        @Index(name = "idx_chat_message_run", columnList = "run_id")
})
public class ChatMessage {

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

    @Column(name = "session_id", nullable = false)
    private Long sessionId;

    /** 父消息 id；首条消息为 null */
    @Column(name = "parent_id")
    private Long parentId;

    /** 当前分支是否激活（同 parent 下仅一条为 true） */
    @Column(name = "is_active", nullable = false)
    private Boolean isActive;

    /** 同 parent 下的兄弟排序；用户切换"上一版/下一版"用 */
    @Column(name = "branch_order", nullable = false)
    private Integer branchOrder;

    /** 关联本轮 Bridge run；仅 ASSISTANT 消息有 */
    @Column(name = "run_id", length = 64)
    private String runId;

    /** USER / ASSISTANT / SYSTEM（SYSTEM 用于压缩摘要） */
    @Column(name = "role", nullable = false, length = 16)
    private String role;

    /** USER 原文 / ASSISTANT 最终回复 / SYSTEM 摘要文本 */
    @Column(name = "content", nullable = false, columnDefinition = "TEXT")
    private String content;

    /**
     * USER: SENT
     * ASSISTANT: RUNNING / SUCCESS / FAILED
     * SYSTEM: SUMMARY
     */
    @Column(name = "status", nullable = false, length = 16)
    private String status;

    /** 实际使用的模型（冗余存储，便于回看当时配置） */
    @Column(name = "model_id")
    private Long modelId;

    /** 实际使用的技能 folderName */
    @Column(name = "skill_folder", length = 255)
    private String skillFolder;

    /** FAILED 时的错误信息 */
    @Column(name = "error", columnDefinition = "TEXT")
    private String error;

    /** 预留：未来支持文件上传时关联附件表 */
    @Column(name = "attachment_id")
    private Long attachmentId;

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

    @Column(name = "completed_at")
    private LocalDateTime completedAt;

    @PrePersist
    protected void onCreate() {
        if (createdAt == null) createdAt = LocalDateTime.now();
        if (isActive == null) isActive = true;
        if (branchOrder == null) branchOrder = 0;
    }
}
