import {
  Column,
  CreateDateColumn,
  Entity,
  Index,
  JoinColumn,
  JoinTable,
  ManyToMany,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm';
import { AiConversation } from './ai-conversation.entity';
import { AiAttachment } from './ai-attachment.entity';
import { AiToolRun } from './ai-tool-run.entity';

export type AiMessageRole = 'user' | 'assistant';
export type AiMessageStatus = 'pending' | 'completed' | 'failed' | 'cancelled';
export type AiMessageFeedback = 'like' | 'dislike';

@Entity('ai_messages')
@Index('idx_ai_messages_conversation_created', ['conversationId', 'createdAt'])
export class AiMessage {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'conversation_id', type: 'integer' })
  conversationId: number;

  @ManyToOne(() => AiConversation, (conversation) => conversation.messages, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'conversation_id' })
  conversation: AiConversation;

  @Column({ type: 'varchar', length: 20 })
  role: AiMessageRole;

  @Column({ type: 'text', default: '' })
  content: string;

  @Column({ name: 'reasoning_content', type: 'text', nullable: true })
  reasoningContent: string | null;

  @Column({ type: 'varchar', length: 20, default: 'completed' })
  status: AiMessageStatus;

  @Column({ name: 'error_code', type: 'varchar', length: 50, nullable: true })
  errorCode: string | null;

  @Column({ name: 'reply_to_message_id', type: 'integer', nullable: true })
  replyToMessageId: number | null;

  @ManyToOne(() => AiMessage, { onDelete: 'SET NULL', nullable: true })
  @JoinColumn({ name: 'reply_to_message_id' })
  replyToMessage: AiMessage | null;

  @Column({ type: 'varchar', length: 20, nullable: true })
  feedback: AiMessageFeedback | null;

  @Column({ name: 'feedback_reason', type: 'varchar', length: 500, nullable: true })
  feedbackReason: string | null;

  @Column({ type: 'simple-json', nullable: true })
  metadata: Record<string, unknown> | null;

  @OneToMany(() => AiToolRun, (run) => run.message)
  toolRuns: AiToolRun[];

  @ManyToMany(() => AiAttachment, (attachment) => attachment.messages)
  @JoinTable({
    name: 'ai_message_attachments',
    joinColumn: { name: 'message_id', referencedColumnName: 'id' },
    inverseJoinColumn: { name: 'attachment_id', referencedColumnName: 'id' },
  })
  attachments: AiAttachment[];

  @CreateDateColumn({ name: 'created_at', type: 'datetime' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'datetime' })
  updatedAt: Date;
}
