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

@Entity('auth_token')
@Index(['token'], { unique: true })
@Index(['userId', 'userType'])
export class AuthToken {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'token', type: 'varchar', length: 500 })
  token: string;

  @Column({ name: 'user_id', type: 'int' })
  userId: number;

  @Column({ name: 'user_type', type: 'varchar', length: 20 })
  userType: string;

  @Column({ name: 'site_id', type: 'int', default: 0 })
  siteId: number;

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

  @Column({ name: 'refresh_token', type: 'varchar', length: 500, nullable: true })
  refreshToken?: string;

  @Column({ name: 'refresh_expires_at', type: 'datetime', nullable: true })
  refreshExpiresAt?: Date;

  @Column({ name: 'ip_address', type: 'varchar', length: 45, nullable: true })
  ipAddress?: string;

  @Column({ name: 'user_agent', type: 'varchar', length: 500, nullable: true })
  userAgent?: string;

  @Column({ name: 'device_type', type: 'varchar', length: 20, nullable: true })
  deviceType?: string;

  @Column({ name: 'is_revoked', type: 'tinyint', default: 0 })
  isRevoked: number;

  @Column({ name: 'revoked_at', type: 'datetime', nullable: true })
  revokedAt?: Date;

  @Column({ name: 'revoked_reason', type: 'varchar', length: 200, nullable: true })
  revokedReason?: string;

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

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

  // 业务逻辑方法 - 与 PHP 项目保持一致
  getDeviceTypeText(): string {
    if (this.deviceType === undefined || this.deviceType === '') return '';
    const typeMap: { [key: string]: string } = {
      'web': '网页',
      'mobile': '手机',
      'app': '应用',
      'wechat': '微信'
    };
    return typeMap[this.deviceType] || '未知';
  }

  getRevokedStatusText(): string {
    return this.isRevoked === 1 ? '已撤销' : '正常';
  }

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

  isRefreshExpired(): boolean {
    if (!this.refreshExpiresAt) return true;
    return new Date() > this.refreshExpiresAt;
  }

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