import {
  Entity,
  Column,
  PrimaryColumn,
  ManyToOne,
  JoinColumn,
  CreateDateColumn,
  BeforeInsert,
} from 'typeorm';
import { User } from './user.entity';
import { DeviceRegistry } from './device-registry.entity';

@Entity('refresh_tokens')
export class RefreshToken {
  @PrimaryColumn({ length: 20 })
  id: string;

  @Column({ name: 'user_id', length: 20 })
  userId: string;

  @Column({ name: 'device_id', length: 20, nullable: true })
  deviceId?: string;

  @Column({ name: 'token_hash', length: 255 })
  tokenHash: string;

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

  @Column({ default: false })
  revoked: boolean;

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

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

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

  @ManyToOne(() => DeviceRegistry, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'device_id' })
  device?: DeviceRegistry;

  @BeforeInsert()
  generateId() {
    if (!this.id) {
      this.id = `rtk_${this.generateNanoId()}`;
    }
  }

  private generateNanoId(): string {
    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < 12; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }
}
