import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
} from 'typeorm';

/**
 * CLIENT OTP LOG ENTITY
 * 
 * Tracks all OTP send/verify attempts for client logins
 * 
 * Why track OTPs separately?
 * - Users table has otpCode for registration
 * - Client portal needs separate OTP tracking for login
 * - Different expiry rules & attempt limits
 * 
 * Lifecycle:
 * 1. Client enters email on /client/login
 * 2. System generates 6-digit OTP
 * 3. Creates ClientOtpLog record (attempts=0, is_verified=0)
 * 4. Sends OTP to phone via SMS
 * 5. Client enters OTP
 * 6. System checks: is_verified=0 and attempts<5 and not expired
 * 7. If match → is_verified=1, verified_at=now
 * 8. If no match → attempts++
 */
@Entity('client_otp_logs')
@Index(['email', 'phone'])
@Index(['expires_at'])
@Index(['is_verified'])
export class ClientOtpLog {
  @PrimaryGeneratedColumn()
  id: number;

  /**
   * Client's email (from access token)
   */
  @Column({ type: 'varchar', length: 255 })
  email: string;

  /**
   * Client's phone number (E.164 format: +971501234567)
   */
  @Column({ type: 'varchar', length: 20 })
  phone: string;

  /**
   * 6-digit OTP code (100000-999999)
   * In real production, might be hashed
   */
  @Column({ type: 'varchar', length: 6 })
  otp_code: string;

  /**
   * How many incorrect attempts so far
   * Max 5 attempts before requiring resend
   */
  @Column({ default: 0 })
  attempts: number;

  /**
   * Has this OTP been successfully verified (0=no, 1=yes)
   * Once verified, this OTP record is no longer usable
   */
  @Column({ default: 0 })
  is_verified: number;

  /**
   * When was this OTP verified (null until verified)
   */
  @Column({ type: 'datetime', nullable: true })
  verified_at: Date;

  /**
   * When does this OTP expire (10 minutes from creation)
   * After expiry, client must request new OTP
   */
  @Column({ type: 'datetime' })
  expires_at: Date;

  /**
   * Timestamp
   */
  @CreateDateColumn()
  created_at: Date;

  /**
   * Helper method: Is OTP still valid for attempts?
   */
  canAttempt(): boolean {
    return this.attempts < 5 && new Date() <= this.expires_at;
  }

  /**
   * Helper method: Is OTP expired?
   */
  isExpired(): boolean {
    return new Date() > this.expires_at;
  }

  /**
   * Helper method: Has max attempts reached?
   */
  maxAttemptsReached(): boolean {
    return this.attempts >= 5;
  }
}
