/**
 * RefreshToken Entity
 *
 * Almacena refresh tokens para autenticación JWT.
 * Permite revocar tokens y gestionar sesiones.
 *
 * @module Auth
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { User } from '../../core/entities/user.entity';

@Entity({ name: 'refresh_tokens', schema: 'auth' })
@Index(['userId', 'revokedAt'])
@Index(['token'])
export class RefreshToken {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

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

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

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

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

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

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

  /**
   * Verificar si el token está expirado
   */
  isExpired(): boolean {
    return this.expiresAt < new Date();
  }

  /**
   * Verificar si el token está revocado
   */
  isRevoked(): boolean {
    return this.revokedAt !== null;
  }

  /**
   * Verificar si el token es válido
   */
  isValid(): boolean {
    return !this.isExpired() && !this.isRevoked();
  }
}
