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

export enum SmsVerificationType {
  REGISTER = 'REGISTER',
  LOGIN = 'LOGIN',
  RESET_PASSWORD = 'RESET_PASSWORD',
  CHANGE_PHONE = 'CHANGE_PHONE',
}

@Entity('sms_verifications')
@Index('idx_sms_verif_phone_type', ['phone', 'type'])
@Index('idx_sms_verif_expires', ['expiresAt'])
export class SmsVerification {
  @PrimaryGeneratedColumn('increment', { type: 'bigint' })
  id: string; // bigint as string in TypeORM

  @Column({ type: 'varchar', length: 20 })
  phone: string;

  @Column({ type: 'varchar', length: 255 })
  code: string;

  @Column({ type: 'varchar', length: 20 })
  type: SmsVerificationType;

  @Column({ name: 'expires_at', type: 'timestamptz' })
  expiresAt: Date;

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

  @Column({ type: 'int', default: 0 })
  attempts: number;

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

  /* ── Domain Methods ── */

  get isExpired(): boolean {
    return new Date() > this.expiresAt;
  }

  get isVerified(): boolean {
    return this.verifiedAt !== null;
  }

  get isValid(): boolean {
    return !this.isExpired && !this.isVerified;
  }

  canAttempt(maxAttempts: number): boolean {
    return this.attempts < maxAttempts;
  }

  incrementAttempts(): void {
    this.attempts += 1;
  }

  markVerified(): void {
    this.verifiedAt = new Date();
  }
}
