/**
 * 消息角色常量
 */
export const MessageRole = {
  USER: 'user',
  ASSISTANT: 'assistant',
  SYSTEM: 'system',
} as const;

export type MessageRoleType = (typeof MessageRole)[keyof typeof MessageRole];

/**
 * 消息类型常量
 */
export const MessageType = {
  TEXT: 'TEXT',
  TEXT_WITH_ATTACHMENTS: 'TEXT_WITH_ATTACHMENTS',
  TOOL_CALL: 'TOOL_CALL',
  TOOL_RESULT: 'TOOL_RESULT',
  PAYMENT_REQUEST: 'PAYMENT_REQUEST',
  ASSESSMENT_START: 'ASSESSMENT_START',
  ASSESSMENT_RESULT: 'ASSESSMENT_RESULT',
} as const;

export type MessageTypeType = (typeof MessageType)[keyof typeof MessageType];

/**
 * Message Domain Entity
 */
export class MessageEntity {
  readonly id: string;
  conversationId: string;
  role: MessageRoleType;
  type: MessageTypeType;
  content: string;
  metadata: Record<string, unknown> | null;
  inputTokens: number | null;
  outputTokens: number | null;
  readonly createdAt: Date;

  private constructor(props: {
    id: string;
    conversationId: string;
    role: MessageRoleType;
    type: MessageTypeType;
    content: string;
    metadata: Record<string, unknown> | null;
    inputTokens: number | null;
    outputTokens: number | null;
    createdAt: Date;
  }) {
    Object.assign(this, props);
  }

  static create(props: {
    id: string;
    conversationId: string;
    role: MessageRoleType;
    type?: MessageTypeType;
    content: string;
    metadata?: Record<string, unknown>;
  }): MessageEntity {
    return new MessageEntity({
      id: props.id,
      conversationId: props.conversationId,
      role: props.role,
      type: props.type || MessageType.TEXT,
      content: props.content,
      metadata: props.metadata || null,
      inputTokens: null,
      outputTokens: null,
      createdAt: new Date(),
    });
  }

  static fromPersistence(props: {
    id: string;
    conversationId: string;
    role: MessageRoleType;
    type: MessageTypeType;
    content: string;
    metadata: Record<string, unknown> | null;
    inputTokens: number | null;
    outputTokens: number | null;
    createdAt: Date;
  }): MessageEntity {
    return new MessageEntity(props);
  }

  setTokenUsage(inputTokens: number, outputTokens: number): void {
    this.inputTokens = inputTokens;
    this.outputTokens = outputTokens;
  }

  isUserMessage(): boolean {
    return this.role === MessageRole.USER;
  }

  isAssistantMessage(): boolean {
    return this.role === MessageRole.ASSISTANT;
  }

  isSystemMessage(): boolean {
    return this.role === MessageRole.SYSTEM;
  }
}
