import {
  Entity,
  Column,
  PrimaryColumn,
  ManyToOne,
  JoinColumn,
  CreateDateColumn,
  BeforeInsert,
} from 'typeorm';
import { Family } from './family.entity';

@Entity('children')
export class Child {
  @PrimaryColumn({ length: 20 })
  id: string;

  @Column({ name: 'family_id', length: 20 })
  familyId: string;

  @Column({ length: 100 })
  name: string;

  @Column({ name: 'birth_date', type: 'timestamp' })
  birthDate: Date;

  @Column({ length: 20, nullable: true })
  gender?: string;

  @Column({ name: 'photo_url', type: 'text', nullable: true })
  photoUrl?: string;

  @Column({ name: 'photo_alt', type: 'text', nullable: true })
  photoAlt?: string;

  @Column({ name: 'display_color', length: 7, default: '#FF6B9D' })
  displayColor: string;

  @Column({ name: 'sort_order', type: 'integer', default: 0 })
  sortOrder: number;

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

  @Column({ name: 'medical_info', type: 'jsonb', default: {} })
  medicalInfo: Record<string, any>;

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

  @Column({ name: 'deleted_at', type: 'timestamp', nullable: true })
  deletedAt?: Date;

  @ManyToOne(() => Family, (family) => family.children, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'family_id' })
  family: Family;

  @BeforeInsert()
  generateId() {
    if (!this.id) {
      this.id = `chd_${this.generateNanoId()}`;
    }
  }

  private generateNanoId(): string {
    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < 12; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }
}
