import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
} from 'typeorm';
import { ReferralCode } from '../value-objects/referral-code.vo';
import { ReferralChain } from '../value-objects/referral-chain.vo';

/**
 * ReferralProfile — 推荐关系聚合根
 *
 * 职责:
 * - 为每个注册用户持有唯一推荐码
 * - 记录推荐人 (usedCode / referrerId)
 * - 维护推荐链 (referralChain)
 * - 统计直推数量
 */
@Entity('referral_profiles')
@Index('idx_referral_profiles_code', ['referralCode'], { unique: true })
@Index('idx_referral_profiles_user', ['userId'], { unique: true })
@Index('idx_referral_profiles_referrer', ['referrerId'])
export class ReferralProfile {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  /** 用户 ID (UUID, 外键指向 users 表) */
  @Column({ name: 'user_id', type: 'uuid' })
  userId: string;

  /** 此用户的推荐码 (用于邀请他人) */
  @Column({ name: 'referral_code', type: 'varchar', length: 20 })
  referralCode: string;

  /** 推荐人 userId (注册时填写的推荐码对应的用户) */
  @Column({ name: 'referrer_id', type: 'uuid', nullable: true })
  referrerId: string | null;

  /** 注册时填写的推荐码 (即推荐人的推荐码) */
  @Column({ name: 'used_code', type: 'varchar', length: 20, nullable: true })
  usedCode: string | null;

  /**
   * 推荐链: [直接推荐人 userId, 推荐人的推荐人 userId, ...]
   * PostgreSQL text[] 类型
   */
  @Column({ name: 'referral_chain', type: 'text', array: true, default: [] })
  referralChain: string[];

  /** 直推下级人数 */
  @Column({ name: 'direct_referral_count', type: 'int', default: 0 })
  directReferralCount: number;

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

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

  /* ── Domain Logic ── */

  /**
   * 工厂方法: 创建新推荐档案
   */
  static create(params: {
    userId: string;
    referralCode: string;
    referrerId: string | null;
    usedCode: string | null;
    referralChain: string[];
  }): ReferralProfile {
    const profile = new ReferralProfile();
    profile.userId = params.userId;
    profile.referralCode = params.referralCode;
    profile.referrerId = params.referrerId;
    profile.usedCode = params.usedCode;
    profile.referralChain = params.referralChain;
    profile.directReferralCount = 0;
    return profile;
  }

  /** 新用户加入后递增直推计数 */
  incrementDirectReferral(): void {
    this.directReferralCount += 1;
  }

  /** 获取推荐链值对象 */
  getChain(): ReferralChain {
    return ReferralChain.fromArray(this.referralChain);
  }

  /** 获取推荐码值对象 */
  getCode(): ReferralCode {
    return ReferralCode.create(this.referralCode);
  }
}
