import {
  Entity,
  Column,
  PrimaryColumn,
  ManyToOne,
  JoinColumn,
  CreateDateColumn,
  BeforeInsert,
  Index,
} from 'typeorm';
import { User } from './user.entity';

@Entity('device_registry')
@Index(['userId', 'deviceFingerprint'], { unique: true })
export class DeviceRegistry {
  @PrimaryColumn({ length: 20 })
  id: string;

  @Column({ name: 'user_id', length: 20 })
  userId: string;

  @Column({ name: 'device_fingerprint', length: 255 })
  deviceFingerprint: string;

  @Column({ length: 20 })
  platform: string;

  @Column({ default: false })
  trusted: boolean;

  @Column({
    name: 'last_seen',
    type: 'timestamp',
    default: () => 'CURRENT_TIMESTAMP',
  })
  lastSeen: Date;

  @ManyToOne(() => User, (user) => user.devices, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'user_id' })
  user: User;

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