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.PreUpdate;
import jakarta.persistence.Table;
import lombok.Data;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * Agent 对话会话主表。
 *
 * <p>对应设计文档 {@code docs/design/agent-chat-page-design.md} §4.1.1。
 * 与 WorkflowRun 解耦——chat 场景有独特的"消息流 + 多轮 + 消息树"结构，
 * 强行塞入 WorkflowRun 会让两类数据互相污染。</p>
 */
@Data
@Entity
@Table(name = "chat_session", indexes = {
        @Index(name = "idx_chat_session_last_msg", columnList = "status, last_message_at"),
        @Index(name = "idx_chat_session_uuid", columnList = "session_uuid", unique = true)
})
public class ChatSession {

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

    /** 对外暴露的 UUID（前端路由用） */
    @Column(name = "session_uuid", nullable = false, length = 36, unique = true)
    private String sessionUuid;

    /** 会话标题；首次 user 消息完成后自动取前 30 字 */
    @Column(name = "title", length = 255)
    private String title;

    /** 当前会话默认模型 id（可切换） */
    @Column(name = "model_id")
    private Long modelId;

    /** 当前会话默认技能 folderName（可切换） */
    @Column(name = "skill_folder", length = 255)
    private String skillFolder;

    /** Hermes Bridge 的 session_id（多轮复用 Agent 实例） */
    @Column(name = "hermes_session", length = 64)
    private String hermesSession;

    /** ACTIVE / ARCHIVED */
    @Column(name = "status", nullable = false, length = 16)
    private String status;

    /**
     * 是否置顶（列表按 pinned DESC, last_message_at DESC 排序）。
     *
     * <p>{@code columnDefinition} 显式带 {@code default false}：
     * 当表已存在数据时，{@code ddl-auto: update} 生成的
     * {@code alter table add column pinned boolean default false not null}
     * 才会被 H2 接受（DEFAULT 子句给已有行填默认值），否则单纯 {@code not null}
     * 会被 H2 拒绝（"NULL not allowed for column PINNED"），导致字段加不上、列表查询全部 500。</p>
     */
    @Column(name = "pinned", nullable = false, columnDefinition = "boolean default false")
    private Boolean pinned = false;

    /** 上游最后一次压缩时间戳（来自压缩事件，用于"中期记忆"视图边界）；首版可留空 */
    @Column(name = "last_summarized_at")
    private LocalDateTime lastSummarizedAt;

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

    /** 用于按最新活动排序 */
    @Column(name = "last_message_at")
    private LocalDateTime lastMessageAt;

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

    @PrePersist
    protected void onCreate() {
        LocalDateTime now = LocalDateTime.now();
        if (createdAt == null) createdAt = now;
        if (updatedAt == null) updatedAt = now;
        if (status == null) status = "ACTIVE";
        if (pinned == null) pinned = false;
        if (sessionUuid == null) sessionUuid = UUID.randomUUID().toString();
        if (hermesSession == null) hermesSession = "chat-" + sessionUuid.replace("-", "").substring(0, 12);
    }

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