import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, LessThan } from 'typeorm';
import { RefreshToken } from '../../domain/entities/refresh-token.entity';
import { IRefreshTokenRepository } from '../../domain/repositories/refresh-token.repository.interface';

@Injectable()
export class RefreshTokenRepository implements IRefreshTokenRepository {
  constructor(
    @InjectRepository(RefreshToken)
    private readonly repo: Repository<RefreshToken>,
  ) {}

  async create(data: Partial<RefreshToken>): Promise<RefreshToken> {
    const token = this.repo.create(data);
    return this.repo.save(token);
  }

  async findByTokenHash(hash: string): Promise<RefreshToken | null> {
    return this.repo.findOne({ where: { tokenHash: hash } });
  }

  async revokeByUserId(userId: string): Promise<void> {
    await this.repo.update(
      { userId, isRevoked: false },
      { isRevoked: true },
    );
  }

  async revokeToken(id: string): Promise<void> {
    await this.repo.update(id, { isRevoked: true });
  }

  async cleanupExpired(): Promise<number> {
    const result = await this.repo.delete({
      expiresAt: LessThan(new Date()),
    });
    return result.affected || 0;
  }
}
