import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { ConversationORM } from './conversation.orm';
import { MessageRoleType, MessageTypeType } from '../../../../domain/entities/message.entity';

/**
 * Message ORM Entity - Database representation
 */
@Entity('messages')
@Index('idx_messages_tenant', ['tenantId'])
@Index('idx_messages_conversation_id', ['conversationId'])
@Index('idx_messages_created_at', ['createdAt'])
@Index('idx_messages_role', ['role'])
export class MessageORM {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ name: 'tenant_id', type: 'uuid' })
  tenantId: string;

  @Column({ name: 'conversation_id', type: 'uuid', nullable: true })
  conversationId: string;

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

  @Column({ type: 'varchar', length: 30, default: 'TEXT' })
  type: MessageTypeType;

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

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

  @Column({ name: 'input_tokens', type: 'int', nullable: true })
  inputTokens: number | null;

  @Column({ name: 'output_tokens', type: 'int', nullable: true })
  outputTokens: number | null;

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

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