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

export enum MfaEventType {
  MFA_SETUP_INITIATED = 'mfa_setup_initiated',
  MFA_SETUP_COMPLETED = 'mfa_setup_completed',
  MFA_DISABLED = 'mfa_disabled',
  TOTP_VERIFIED = 'totp_verified',
  TOTP_FAILED = 'totp_failed',
  BACKUP_CODE_USED = 'backup_code_used',
  BACKUP_CODES_REGENERATED = 'backup_codes_regenerated',
  DEVICE_TRUSTED = 'device_trusted',
  DEVICE_REVOKED = 'device_revoked',
  ANOMALY_DETECTED = 'anomaly_detected',
  ACCOUNT_LOCKED = 'account_locked',
  ACCOUNT_UNLOCKED = 'account_unlocked',
}

@Entity({ schema: 'auth', name: 'mfa_audit_log' })
@Index('idx_mfa_audit_user', ['userId', 'createdAt'])
@Index('idx_mfa_audit_event', ['eventType', 'createdAt'])
@Index('idx_mfa_audit_failures', ['userId', 'createdAt'], {
  where: 'success = FALSE',
})
export class MfaAuditLog {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({
    type: 'enum',
    enum: MfaEventType,
    nullable: false,
    name: 'event_type',
  })
  eventType: MfaEventType;

  @Column({ type: 'boolean', nullable: false })
  success: boolean;

  @Column({ type: 'varchar', length: 128, nullable: true, name: 'failure_reason' })
  failureReason: string | null;

  @Column({ type: 'inet', nullable: true, name: 'ip_address' })
  ipAddress: string | null;

  @Column({ type: 'text', nullable: true, name: 'user_agent' })
  userAgent: string | null;

  @Column({
    type: 'varchar',
    length: 128,
    nullable: true,
    name: 'device_fingerprint',
  })
  deviceFingerprint: string | null;

  @Column({ type: 'jsonb', nullable: true })
  location: Record<string, unknown> | null;

  @Column({ type: 'jsonb', default: {}, nullable: true })
  metadata: Record<string, unknown>;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'user_id' })
  user: User;

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