import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, ManyToOne, JoinColumn } from 'typeorm';
import { File } from '@/server/modules/files/file.entity';
import { UserEntity } from '@/server/modules/users/user.entity';
import { UserType } from '@/server/modules/users/user.enum';

@Entity('chat_messages')
export class ChatMessage {
  @PrimaryGeneratedColumn({ unsigned: true })
  id!: number;

  @Column({ name: 'class_id', type: 'varchar', length: 255, comment: '课堂ID' })
  classId!: string;

  @Column({ 
    name: 'type', 
    type: 'enum', 
    enum: ['text', 'image', 'system'], 
    comment: '消息类型' 
  })
  type!: 'text' | 'image' | 'system';

  @Column({ name: 'content', type: 'text', comment: '消息内容' })
  content!: string;

  @Column({ 
    name: 'file_id', 
    type: 'int', 
    unsigned: true, 
    nullable: true, 
    comment: '关联文件ID（用于图片消息）' 
  })
  fileId!: number | null;

  @ManyToOne(() => File, { nullable: true })
  @JoinColumn({ 
    name: 'file_id', 
    referencedColumnName: 'id' 
  })
  file!: File | null;

  @Column({ 
    name: 'sender_id', 
    type: 'int', 
    unsigned: true, 
    nullable: true, 
    comment: '发送者ID' 
  })
  senderId!: number | null;

  @ManyToOne(() => UserEntity, { nullable: true })
  @JoinColumn({ 
    name: 'sender_id',
    referencedColumnName: 'id'
  })
  sender!: UserEntity | null;

  @Column({ 
    name: 'sender_name', 
    type: 'varchar', 
    length: 255, 
    nullable: true, 
    comment: '发送者名称' 
  })
  senderName!: string | null;

  @Column({ 
    name: 'sender_type', 
    type: 'enum', 
    enum: UserType, 
    nullable: true, 
    comment: '发送者类型（teacher/student/trainee）' 
  })
  senderType!: UserType | null;

  @Column({ name: 'timestamp', type: 'bigint', comment: '消息时间戳' })
  timestamp!: number;

  // 操作人跟踪字段
  @Column({ 
    name: 'created_by', 
    type: 'int', 
    nullable: true, 
    comment: '创建用户ID' 
  })
  createdBy!: number | null;

  @Column({ 
    name: 'updated_by', 
    type: 'int', 
    nullable: true, 
    comment: '更新用户ID' 
  })
  updatedBy!: number | null;

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

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