import {
  Entity,
  Column,
  PrimaryColumn,
  CreateDateColumn,
  UpdateDateColumn,
  OneToMany,
  BeforeInsert,
} from 'typeorm';
import { DeviceRegistry } from './device-registry.entity';
import { FamilyMember } from './family-member.entity';

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

  @Column({ length: 255, unique: true })
  email: string;

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

  @Column({ name: 'password_hash', length: 255 })
  passwordHash: string;

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

  @Column({ length: 10, default: 'en-US' })
  locale: string;

  @Column({ length: 50, default: 'UTC' })
  timezone: string;

  @Column({ name: 'email_verified', default: false })
  emailVerified: boolean;

  @Column({ name: 'email_verification_token', length: 64, nullable: true })
  emailVerificationToken?: string | null;

  @Column({
    name: 'email_verification_sent_at',
    type: 'timestamp without time zone',
    nullable: true,
  })
  emailVerificationSentAt?: Date | null;

  // MFA fields
  @Column({ name: 'mfa_enabled', default: false })
  mfaEnabled: boolean;

  @Column({ name: 'mfa_method', length: 20, nullable: true })
  mfaMethod?: 'totp' | 'email' | null;

  @Column({ name: 'totp_secret', length: 32, nullable: true })
  totpSecret?: string | null;

  @Column({ name: 'mfa_backup_codes', type: 'jsonb', nullable: true })
  mfaBackupCodes?: string[] | null;

  @Column({ name: 'email_mfa_code', length: 6, nullable: true })
  emailMfaCode?: string | null;

  @Column({
    name: 'email_mfa_code_expires_at',
    type: 'timestamp without time zone',
    nullable: true,
  })
  emailMfaCodeExpiresAt?: Date | null;

  // COPPA compliance fields
  @Column({ name: 'date_of_birth', type: 'date', nullable: true })
  dateOfBirth?: Date | null;

  @Column({ name: 'coppa_consent_given', default: false })
  coppaConsentGiven: boolean;

  @Column({
    name: 'coppa_consent_date',
    type: 'timestamp without time zone',
    nullable: true,
  })
  coppaConsentDate?: Date | null;

  @Column({ name: 'parental_email', length: 255, nullable: true })
  parentalEmail?: string | null;

  @Column({ type: 'jsonb', nullable: true })
  preferences?: {
    notifications?: boolean;
    emailUpdates?: boolean;
    darkMode?: boolean;
  };

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

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

  @OneToMany(() => DeviceRegistry, (device) => device.user)
  devices: DeviceRegistry[];

  @OneToMany(() => FamilyMember, (familyMember) => familyMember.user)
  familyMemberships: FamilyMember[];

  @BeforeInsert()
  generateId() {
    if (!this.id) {
      this.id = `usr_${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;
  }
}
