import { Repository, IsNull, MoreThan } from 'typeorm';
import { AppDataSource } from '../index';
import { PasswordResetToken } from '../entities/PasswordResetToken.entity';

export class PasswordResetTokenRepository {
  private repo: Repository<PasswordResetToken>;

  constructor() {
    this.repo = AppDataSource.getRepository(PasswordResetToken);
  }

  create(data: Partial<PasswordResetToken>): Promise<PasswordResetToken> {
    const row = this.repo.create(data);
    return this.repo.save(row);
  }

  findValidByHash(tokenHash: string): Promise<PasswordResetToken | null> {
    return this.repo.findOne({
      where: {
        tokenHash,
        usedAt: IsNull(),
        expiresAt: MoreThan(new Date()),
      },
      relations: ['user'],
    });
  }

  async markUsed(id: string): Promise<void> {
    await this.repo.update(id, { usedAt: new Date() });
  }

  async invalidateForUser(userId: string): Promise<void> {
    await this.repo.update({ userId, usedAt: IsNull() }, { usedAt: new Date() });
  }
}
