import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  OneToMany,
} from 'typeorm';
import { MessageEntity } from './message.entity';

/**
 * 对话状态常量
 */
export const ConversationStatus = {
  ACTIVE: 'ACTIVE',
  ENDED: 'ENDED',
  ARCHIVED: 'ARCHIVED',
} as const;

export type ConversationStatusType =
  (typeof ConversationStatus)[keyof typeof ConversationStatus];

/**
 * 咨询阶段常量
 */
export const ConsultingStage = {
  GREETING: 'greeting',
  NEEDS_DISCOVERY: 'needs_discovery',
  INFO_COLLECTION: 'info_collection',
  ASSESSMENT: 'assessment',
  RECOMMENDATION: 'recommendation',
  OBJECTION_HANDLING: 'objection_handling',
  CONVERSION: 'conversion',
  HANDOFF: 'handoff',
} as const;

export type ConsultingStageType =
  (typeof ConsultingStage)[keyof typeof ConsultingStage];

/**
 * 咨询状态结构（存储为JSON）
 */
export interface ConsultingStateJson {
  strategyId: string;
  currentStageId: string;
  stageTurnCount: number;
  collectedInfo: Record<string, unknown>;
  assessmentResult?: {
    recommendedPrograms: string[];
    suitabilityScore: number;
    highlights: string[];
    concerns: string[];
  };
  conversionPath?: string;
  stageHistory: Array<{
    stageId: string;
    enteredAt: string;
    exitedAt?: string;
    turnsInStage: number;
  }>;
}

@Entity('conversations')
export class ConversationEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ length: 20, default: 'ACTIVE' })
  status: ConversationStatusType;

  @Column({ nullable: true })
  title: string;

  @Column({ type: 'text', nullable: true })
  summary: string;

  @Column({ length: 50, nullable: true })
  category: string;

  @Column({ name: 'message_count', default: 0 })
  messageCount: number;

  // ========== V2新增：咨询流程字段 ==========

  /**
   * 当前咨询阶段
   */
  @Column({
    name: 'consulting_stage',
    length: 30,
    default: 'greeting',
    nullable: true,
  })
  consultingStage: ConsultingStageType;

  /**
   * 咨询状态（完整的状态对象，包含收集的信息、评估结果等）
   */
  @Column({
    name: 'consulting_state',
    type: 'jsonb',
    nullable: true,
  })
  consultingState: ConsultingStateJson;

  /**
   * 已收集的用户信息（快速查询用，与consultingState中的collectedInfo同步）
   */
  @Column({
    name: 'collected_info',
    type: 'jsonb',
    nullable: true,
  })
  collectedInfo: Record<string, unknown>;

  /**
   * 推荐的移民方案（评估后填充）
   */
  @Column({
    name: 'recommended_programs',
    type: 'text',
    array: true,
    nullable: true,
  })
  recommendedPrograms: string[];

  /**
   * 转化路径（用户选择的下一步）
   */
  @Column({
    name: 'conversion_path',
    length: 30,
    nullable: true,
  })
  conversionPath: string;

  /**
   * 用户设备信息（用于破冰）
   */
  @Column({
    name: 'device_info',
    type: 'jsonb',
    nullable: true,
  })
  deviceInfo: {
    ip?: string;
    userAgent?: string;
    fingerprint?: string;
    region?: string;
  };

  // ========== 原有字段 ==========

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

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

  @Column({ name: 'ended_at', nullable: true })
  endedAt: Date;

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