import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
  OneToMany,
} from 'typeorm';
import { User } from '../../user/user.entity';
import { KnowledgeBase } from '../../knowledge-base/knowledge-base.entity';
import { KnowledgeGroup } from '../../knowledge-group/knowledge-group.entity';
import type { AssessmentQuestion } from './assessment-question.entity';
import { AssessmentTemplate } from './assessment-template.entity';

export enum AssessmentStatus {
  IN_PROGRESS = 'IN_PROGRESS',
  COMPLETED = 'COMPLETED',
}

@Entity('assessment_sessions')
export class AssessmentSession {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ name: 'user_id' })
  userId: string;

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

  @Column({ name: 'tenant_id', nullable: true })
  tenantId: string;

  @Column({ name: 'knowledge_base_id', nullable: true })
  knowledgeBaseId: string | null;

  @ManyToOne(() => KnowledgeBase, { nullable: true })
  @JoinColumn({ name: 'knowledge_base_id' })
  knowledgeBase: KnowledgeBase;

  @Column({ name: 'knowledge_group_id', nullable: true })
  knowledgeGroupId: string | null;

  @ManyToOne(() => KnowledgeGroup, { nullable: true })
  @JoinColumn({ name: 'knowledge_group_id' })
  knowledgeGroup: KnowledgeGroup;

  @Column({ name: 'thread_id', nullable: true })
  threadId: string;

  @Column({
    type: 'varchar',
    enum: AssessmentStatus,
    default: AssessmentStatus.IN_PROGRESS,
  })
  status: AssessmentStatus;

  @Column({ type: 'float', name: 'final_score', nullable: true })
  finalScore: number;

  @Column({ type: 'text', name: 'final_report', nullable: true })
  finalReport: string;

  @Column({ type: 'simple-json', nullable: true })
  messages: any[];

  @Column({ type: 'simple-json', name: 'feedback_history', nullable: true })
  feedbackHistory: any[];

  @Column({ type: 'int', name: 'current_question_index', default: 0 })
  currentQuestionIndex: number;

  @Column({ type: 'int', name: 'follow_up_count', default: 0 })
  followUpCount: number;

  @Column({ type: 'simple-json', nullable: true })
  questions_json: any[];

  @Column({ type: 'varchar', length: 10, default: 'zh' })
  language: string;

  @Column({ name: 'template_id', nullable: true })
  templateId: string;

  @ManyToOne(() => AssessmentTemplate, { nullable: true })
  @JoinColumn({ name: 'template_id' })
  template: AssessmentTemplate;

  @Column({ type: 'simple-json', name: 'template_json', nullable: true })
  templateJson: any;

  @OneToMany(
    'AssessmentQuestion',
    (question: AssessmentQuestion) => question.session,
  )
  questions: AssessmentQuestion[];

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

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