import { Injectable } from '@nestjs/common';
import { v4 as uuidv4 } from 'uuid';
import { AuthToken } from '../entities/token.entity';

@Injectable()
export class TokenService {
  // En una implementación real esto debería usar el repositorio de MikroORM.
  private tokens: AuthToken[] = [];

  createToken(name?: string, expiresInHours?: number): AuthToken {
    const token = new AuthToken();
    token.token = uuidv4();
    token.name = name;
    if (expiresInHours) {
      token.expiresAt = new Date(Date.now() + expiresInHours * 60 * 60 * 1000);
    }
    this.tokens.push(token);
    return token;
  }

  validate(tokenString: string): AuthToken | null {
    const token = this.tokens.find((t) => t.token === tokenString);
    if (!token) return null;
    if (token.expiresAt && token.expiresAt < new Date()) return null;
    return token;
  }
}
