import { Injectable } from '@nestjs/common';
import { PrismaService } from '@modules/shared';
import {
  type IRefreshTokenRepository,
  type RefreshTokenRecord,
} from '../../domain/repositories/refresh-token.repository';

@Injectable()
export class PrismaRefreshTokenRepository implements IRefreshTokenRepository {
  constructor(private readonly prisma: PrismaService) {}

  async create(
    record: Omit<RefreshTokenRecord, 'id' | 'createdAt'>,
  ): Promise<RefreshTokenRecord> {
    return this.prisma.refreshToken.create({
      data: {
        userId: record.userId,
        token: record.token,
        family: record.family,
        expiresAt: record.expiresAt,
        revokedAt: record.revokedAt,
      },
    });
  }

  async findByToken(token: string): Promise<RefreshTokenRecord | null> {
    return this.prisma.refreshToken.findUnique({ where: { token } });
  }

  async revokeByFamily(family: string): Promise<void> {
    await this.prisma.refreshToken.updateMany({
      where: { family, revokedAt: null },
      data: { revokedAt: new Date() },
    });
  }

  async revokeAllForUser(userId: string): Promise<void> {
    await this.prisma.refreshToken.updateMany({
      where: { userId, revokedAt: null },
      data: { revokedAt: new Date() },
    });
  }

  async deleteExpired(): Promise<number> {
    const result = await this.prisma.refreshToken.deleteMany({
      where: { expiresAt: { lt: new Date() } },
    });
    return result.count;
  }
}
