/**
 * 婚姻状态
 */
export enum MaritalStatus {
  SINGLE = 'SINGLE',
  MARRIED = 'MARRIED',
  DIVORCED = 'DIVORCED',
  WIDOWED = 'WIDOWED',
}

/**
 * 移民类型
 */
export enum ImmigrationType {
  SKILLED = 'SKILLED',           // 技术移民
  INVESTMENT = 'INVESTMENT',     // 投资移民
  BUSINESS = 'BUSINESS',         // 企业家移民
  STUDY = 'STUDY',               // 留学移民
  FAMILY = 'FAMILY',             // 家庭团聚
  REFUGEE = 'REFUGEE',           // 难民/庇护
  WORK_PERMIT = 'WORK_PERMIT',   // 工作签证
}

/**
 * 计划时间线
 */
export enum PlannedTimeline {
  WITHIN_6M = 'WITHIN_6M',       // 6个月内
  WITHIN_1Y = 'WITHIN_1Y',       // 1年内
  ONE_TO_TWO_Y = '1_2Y',         // 1-2年
  TWO_TO_THREE_Y = '2_3Y',       // 2-3年
  NO_PLAN = 'NO_PLAN',           // 暂无明确计划
}

/**
 * 净资产范围
 */
export enum NetWorthRange {
  UNDER_500K = 'UNDER_500K',     // <50万
  FROM_500K_1M = '500K_1M',      // 50-100万
  FROM_1M_5M = '1M_5M',          // 100-500万
  FROM_5M_10M = '5M_10M',        // 500-1000万
  OVER_10M = 'OVER_10M',         // >1000万
}

/**
 * 学历等级
 */
export enum EducationLevel {
  HIGH_SCHOOL = 'HIGH_SCHOOL',
  ASSOCIATE = 'ASSOCIATE',       // 大专
  BACHELOR = 'BACHELOR',         // 本科
  MASTER = 'MASTER',             // 硕士
  DOCTORATE = 'DOCTORATE',       // 博士
  OTHER = 'OTHER',
}

/**
 * 教育记录
 */
export interface EducationRecord {
  level: EducationLevel;
  major: string;
  institution: string;
  country: string;
  graduationYear: number;
  isWesEvaluated?: boolean;      // 是否WES认证
}

/**
 * 工作记录
 */
export interface WorkRecord {
  jobTitle: string;
  nocCode?: string;              // 加拿大NOC代码
  employer: string;
  country: string;
  startDate: string;             // YYYY-MM
  endDate?: string;              // YYYY-MM or null for current
  isCurrent: boolean;
  isManagement: boolean;
}

/**
 * 语言成绩
 */
export interface LanguageScore {
  language: 'ENGLISH' | 'FRENCH' | 'OTHER';
  testType: string;              // IELTS, TOEFL, TEF, TCF, etc.
  overallScore: number;
  listening?: number;
  reading?: number;
  writing?: number;
  speaking?: number;
  testDate: string;              // YYYY-MM-DD
  expiryDate?: string;           // YYYY-MM-DD
}

/**
 * 家庭成员
 */
export interface FamilyMember {
  relationship: 'SPOUSE' | 'CHILD' | 'PARENT' | 'SIBLING';
  birthYear: number;
  nationality: string;
  willAccompany: boolean;        // 是否随行
  educationLevel?: EducationLevel;
  hasWorkExperience?: boolean;
}

/**
 * User Profile Domain Entity
 * 用户移民档案
 */
export class UserProfileEntity {
  readonly id: string;
  readonly userId: string;

  // 基本信息
  fullName: string | null;
  birthDate: Date | null;
  nationality: string | null;
  currentCountry: string | null;
  currentCity: string | null;
  maritalStatus: MaritalStatus | null;

  // 移民意向
  targetCountries: string[];           // ISO 3166-1 alpha-2 codes
  immigrationTypes: ImmigrationType[];
  plannedTimeline: PlannedTimeline | null;
  primaryPurpose: string | null;       // 移民主要目的

  // 教育背景
  highestEducation: EducationLevel | null;
  educationRecords: EducationRecord[];

  // 工作经历
  currentOccupation: string | null;
  totalWorkYears: number | null;
  workRecords: WorkRecord[];

  // 语言能力
  languageScores: LanguageScore[];

  // 家庭信息
  familyMembers: FamilyMember[];

  // 资产信息 (投资移民用)
  netWorthRange: NetWorthRange | null;
  hasBusinessExperience: boolean;
  businessYears: number | null;

  // 其他
  hasOverseasExperience: boolean;      // 海外经历
  hasCriminalRecord: boolean | null;   // 犯罪记录
  hasHealthIssues: boolean | null;     // 健康问题
  additionalNotes: string | null;      // 补充说明

  // 完成度
  completionPercentage: number;

  readonly createdAt: Date;
  updatedAt: Date;

  private constructor(props: Partial<UserProfileEntity> & { id: string; userId: string }) {
    this.id = props.id;
    this.userId = props.userId;

    this.fullName = props.fullName ?? null;
    this.birthDate = props.birthDate ?? null;
    this.nationality = props.nationality ?? null;
    this.currentCountry = props.currentCountry ?? null;
    this.currentCity = props.currentCity ?? null;
    this.maritalStatus = props.maritalStatus ?? null;

    this.targetCountries = props.targetCountries ?? [];
    this.immigrationTypes = props.immigrationTypes ?? [];
    this.plannedTimeline = props.plannedTimeline ?? null;
    this.primaryPurpose = props.primaryPurpose ?? null;

    this.highestEducation = props.highestEducation ?? null;
    this.educationRecords = props.educationRecords ?? [];

    this.currentOccupation = props.currentOccupation ?? null;
    this.totalWorkYears = props.totalWorkYears ?? null;
    this.workRecords = props.workRecords ?? [];

    this.languageScores = props.languageScores ?? [];

    this.familyMembers = props.familyMembers ?? [];

    this.netWorthRange = props.netWorthRange ?? null;
    this.hasBusinessExperience = props.hasBusinessExperience ?? false;
    this.businessYears = props.businessYears ?? null;

    this.hasOverseasExperience = props.hasOverseasExperience ?? false;
    this.hasCriminalRecord = props.hasCriminalRecord ?? null;
    this.hasHealthIssues = props.hasHealthIssues ?? null;
    this.additionalNotes = props.additionalNotes ?? null;

    this.completionPercentage = props.completionPercentage ?? 0;

    this.createdAt = props.createdAt ?? new Date();
    this.updatedAt = props.updatedAt ?? new Date();
  }

  /**
   * Create a new empty profile for user
   */
  static create(userId: string): UserProfileEntity {
    return new UserProfileEntity({
      id: crypto.randomUUID(),
      userId,
      createdAt: new Date(),
      updatedAt: new Date(),
    });
  }

  /**
   * Reconstruct from persistence
   */
  static fromPersistence(props: {
    id: string;
    userId: string;
    fullName: string | null;
    birthDate: Date | null;
    nationality: string | null;
    currentCountry: string | null;
    currentCity: string | null;
    maritalStatus: string | null;
    targetCountries: string[];
    immigrationTypes: string[];
    plannedTimeline: string | null;
    primaryPurpose: string | null;
    highestEducation: string | null;
    educationRecords: EducationRecord[];
    currentOccupation: string | null;
    totalWorkYears: number | null;
    workRecords: WorkRecord[];
    languageScores: LanguageScore[];
    familyMembers: FamilyMember[];
    netWorthRange: string | null;
    hasBusinessExperience: boolean;
    businessYears: number | null;
    hasOverseasExperience: boolean;
    hasCriminalRecord: boolean | null;
    hasHealthIssues: boolean | null;
    additionalNotes: string | null;
    completionPercentage: number;
    createdAt: Date;
    updatedAt: Date;
  }): UserProfileEntity {
    return new UserProfileEntity({
      ...props,
      maritalStatus: props.maritalStatus as MaritalStatus | null,
      immigrationTypes: props.immigrationTypes as ImmigrationType[],
      plannedTimeline: props.plannedTimeline as PlannedTimeline | null,
      highestEducation: props.highestEducation as EducationLevel | null,
      netWorthRange: props.netWorthRange as NetWorthRange | null,
    });
  }

  /**
   * Update basic info
   */
  updateBasicInfo(data: {
    fullName?: string;
    birthDate?: Date;
    nationality?: string;
    currentCountry?: string;
    currentCity?: string;
    maritalStatus?: MaritalStatus;
  }): void {
    if (data.fullName !== undefined) this.fullName = data.fullName;
    if (data.birthDate !== undefined) this.birthDate = data.birthDate;
    if (data.nationality !== undefined) this.nationality = data.nationality;
    if (data.currentCountry !== undefined) this.currentCountry = data.currentCountry;
    if (data.currentCity !== undefined) this.currentCity = data.currentCity;
    if (data.maritalStatus !== undefined) this.maritalStatus = data.maritalStatus;
    this.recalculateCompletion();
    this.updatedAt = new Date();
  }

  /**
   * Update immigration intent
   */
  updateImmigrationIntent(data: {
    targetCountries?: string[];
    immigrationTypes?: ImmigrationType[];
    plannedTimeline?: PlannedTimeline;
    primaryPurpose?: string;
  }): void {
    if (data.targetCountries !== undefined) this.targetCountries = data.targetCountries;
    if (data.immigrationTypes !== undefined) this.immigrationTypes = data.immigrationTypes;
    if (data.plannedTimeline !== undefined) this.plannedTimeline = data.plannedTimeline;
    if (data.primaryPurpose !== undefined) this.primaryPurpose = data.primaryPurpose;
    this.recalculateCompletion();
    this.updatedAt = new Date();
  }

  /**
   * Update education
   */
  updateEducation(data: {
    highestEducation?: EducationLevel;
    educationRecords?: EducationRecord[];
  }): void {
    if (data.highestEducation !== undefined) this.highestEducation = data.highestEducation;
    if (data.educationRecords !== undefined) this.educationRecords = data.educationRecords;
    this.recalculateCompletion();
    this.updatedAt = new Date();
  }

  /**
   * Update work experience
   */
  updateWorkExperience(data: {
    currentOccupation?: string;
    totalWorkYears?: number;
    workRecords?: WorkRecord[];
  }): void {
    if (data.currentOccupation !== undefined) this.currentOccupation = data.currentOccupation;
    if (data.totalWorkYears !== undefined) this.totalWorkYears = data.totalWorkYears;
    if (data.workRecords !== undefined) this.workRecords = data.workRecords;
    this.recalculateCompletion();
    this.updatedAt = new Date();
  }

  /**
   * Update language scores
   */
  updateLanguageScores(scores: LanguageScore[]): void {
    this.languageScores = scores;
    this.recalculateCompletion();
    this.updatedAt = new Date();
  }

  /**
   * Update family members
   */
  updateFamilyMembers(members: FamilyMember[]): void {
    this.familyMembers = members;
    this.recalculateCompletion();
    this.updatedAt = new Date();
  }

  /**
   * Update financial info
   */
  updateFinancialInfo(data: {
    netWorthRange?: NetWorthRange;
    hasBusinessExperience?: boolean;
    businessYears?: number;
  }): void {
    if (data.netWorthRange !== undefined) this.netWorthRange = data.netWorthRange;
    if (data.hasBusinessExperience !== undefined) this.hasBusinessExperience = data.hasBusinessExperience;
    if (data.businessYears !== undefined) this.businessYears = data.businessYears;
    this.recalculateCompletion();
    this.updatedAt = new Date();
  }

  /**
   * Calculate profile completion percentage
   */
  private recalculateCompletion(): void {
    let filled = 0;
    const total = 10;

    if (this.fullName && this.birthDate && this.nationality) filled++;
    if (this.currentCountry) filled++;
    if (this.targetCountries.length > 0) filled++;
    if (this.immigrationTypes.length > 0) filled++;
    if (this.highestEducation) filled++;
    if (this.educationRecords.length > 0) filled++;
    if (this.currentOccupation || this.workRecords.length > 0) filled++;
    if (this.languageScores.length > 0) filled++;
    if (this.maritalStatus) filled++;
    if (this.plannedTimeline) filled++;

    this.completionPercentage = Math.round((filled / total) * 100);
  }

  /**
   * Get age from birth date
   */
  getAge(): number | null {
    if (!this.birthDate) return null;
    const today = new Date();
    let age = today.getFullYear() - this.birthDate.getFullYear();
    const monthDiff = today.getMonth() - this.birthDate.getMonth();
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < this.birthDate.getDate())) {
      age--;
    }
    return age;
  }
}
