import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  DeleteDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
  Unique,
} from 'typeorm';
import { Device, BiometricType } from './device.entity';

@Entity({ name: 'biometric_credentials', schema: 'auth' })
@Unique(['deviceId', 'credentialId'])
export class BiometricCredential {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'device_id', type: 'uuid' })
  deviceId: string;

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

  // Tipo de biometrico
  @Index()
  @Column({ name: 'biometric_type', type: 'varchar', length: 50 })
  biometricType: BiometricType;

  // Credencial (public key para WebAuthn/FIDO2)
  @Column({ name: 'credential_id', type: 'text' })
  credentialId: string;

  @Column({ name: 'public_key', type: 'text' })
  publicKey: string;

  @Column({ type: 'varchar', length: 20, default: 'ES256' })
  algorithm: string;

  // Metadata
  @Column({ name: 'credential_name', type: 'varchar', length: 100, nullable: true })
  credentialName: string; // "Huella indice derecho", "Face ID iPhone"

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

  // Estado
  @Column({ name: 'is_active', type: 'boolean', default: true })
  isActive: boolean;

  @Column({ name: 'last_used_at', type: 'timestamptz', nullable: true })
  lastUsedAt: Date;

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

  // Seguridad
  @Column({ name: 'failed_attempts', type: 'integer', default: 0 })
  failedAttempts: number;

  @Column({ name: 'locked_until', type: 'timestamptz', nullable: true })
  lockedUntil: Date;

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

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

  @DeleteDateColumn({ name: 'deleted_at', type: 'timestamptz', nullable: true })
  deletedAt: Date;

  // Relaciones
  @ManyToOne(() => Device, (device) => device.biometricCredentials, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'device_id' })
  device: Device;
}
