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

export enum MfaDeviceType {
  TOTP = 'totp',
  SMS = 'sms',
  EMAIL = 'email',
  HARDWARE_KEY = 'hardware_key',
}

@Entity({ schema: 'auth', name: 'mfa_devices' })
@Index('idx_mfa_devices_user', ['userId'])
@Index('idx_mfa_devices_primary', ['userId', 'isPrimary'])
export class MfaDevice {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid', nullable: false, name: 'user_id' })
  userId: string;

  // Device info
  @Column({ type: 'varchar', length: 50, nullable: false, name: 'device_type' })
  deviceType: string;

  @Column({
    type: 'varchar',
    length: 255,
    nullable: true,
    name: 'device_name',
  })
  deviceName: string | null;

  // TOTP specific
  @Column({ type: 'text', nullable: true, name: 'secret_encrypted' })
  secretEncrypted: string | null;

  // Status
  @Column({ type: 'boolean', default: false, name: 'is_primary' })
  isPrimary: boolean;

  @Column({ type: 'boolean', default: false, name: 'is_verified' })
  isVerified: boolean;

  @Column({ type: 'timestamptz', nullable: true, name: 'verified_at' })
  verifiedAt: Date | null;

  // Usage tracking
  @Column({ type: 'timestamptz', nullable: true, name: 'last_used_at' })
  lastUsedAt: Date | null;

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

  // Timestamps
  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt: Date;

  @Column({ type: 'timestamptz', nullable: true, name: 'disabled_at' })
  disabledAt: Date | null;

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