import {
  Entity,
  Column,
  PrimaryColumn,
  ManyToOne,
  OneToMany,
  JoinColumn,
  CreateDateColumn,
  BeforeInsert,
} from 'typeorm';
import { User } from './user.entity';
import { FamilyMember } from './family-member.entity';
import { Child } from './child.entity';

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

  @Column({ length: 100, nullable: true })
  name?: string;

  @Column({ name: 'share_code', length: 10, unique: true })
  shareCode: string;

  @Column({ name: 'created_by', length: 20 })
  createdBy: string;

  @Column({ name: 'subscription_tier', length: 20, default: 'free' })
  subscriptionTier: string;

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

  @ManyToOne(() => User)
  @JoinColumn({ name: 'created_by' })
  creator: User;

  @OneToMany(() => FamilyMember, (member) => member.family)
  members: FamilyMember[];

  @OneToMany(() => Child, (child) => child.family)
  children: Child[];

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

  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;
  }

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