import {
  Column,
  CreateDateColumn,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm';
import { User } from '../../entities/user.entity';
import { AiMessage } from './ai-message.entity';

@Entity('ai_conversations')
@Index('idx_ai_conversations_user_last_message', ['userId', 'lastMessageAt'])
export class AiConversation {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'user_id', type: 'integer' })
  userId: number;

  @ManyToOne(() => User, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'user_id' })
  user: User;

  @Column({ type: 'varchar', length: 100, default: '新对话' })
  title: string;

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

  @OneToMany(() => AiMessage, (message) => message.conversation)
  messages: AiMessage[];

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

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

  @Column({ name: 'last_message_at', type: 'datetime', nullable: true })
  lastMessageAt: Date | null;
}
