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

export enum DevicePlatform {
  ANDROID = 'ANDROID',
  IOS = 'IOS',
}

export enum PushChannel {
  FCM = 'FCM',
  APNS = 'APNS',
  HMS = 'HMS',
  XIAOMI = 'XIAOMI',
  OPPO = 'OPPO',
  VIVO = 'VIVO',
}

@Entity('device_tokens')
@Index('idx_device_tokens_token', ['token'], { unique: true })
@Index('idx_device_tokens_user_active', ['userId', 'isActive'])
export class DeviceToken {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

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

  @Column({ type: 'text' })
  token: string;

  @Column({ name: 'device_id', type: 'varchar', length: 200, nullable: true })
  deviceId: string | null;

  @Column({ name: 'device_model', type: 'varchar', length: 200, nullable: true })
  deviceModel: string | null;

  @Column({ name: 'app_version', type: 'varchar', length: 50, nullable: true })
  appVersion: string | null;

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

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

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

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

  // ── Domain Methods ──

  isExpired(maxAgeDays = 90): boolean {
    if (!this.lastUsedAt) return false;
    const diffMs = Date.now() - this.lastUsedAt.getTime();
    return diffMs > maxAgeDays * 24 * 60 * 60 * 1000;
  }
}
