import { Injectable } from '@nestjs/common';
import { PrismaService } from '@modules/shared';
import {
  type IMfaChallengeRepository,
  type MfaChallengeRecord,
} from '../../domain/repositories/mfa-challenge.repository';

@Injectable()
export class PrismaMfaChallengeRepository implements IMfaChallengeRepository {
  constructor(private readonly prisma: PrismaService) {}

  async create(
    record: Omit<MfaChallengeRecord, 'createdAt'>,
  ): Promise<MfaChallengeRecord> {
    return this.prisma.mfaChallenge.create({ data: record });
  }

  async findById(id: string): Promise<MfaChallengeRecord | null> {
    return this.prisma.mfaChallenge.findUnique({ where: { id } });
  }

  async incrementAttempts(id: string): Promise<void> {
    await this.prisma.mfaChallenge.update({
      where: { id },
      data: { attemptCount: { increment: 1 } },
    });
  }

  async markVerified(id: string): Promise<void> {
    await this.prisma.mfaChallenge.update({
      where: { id },
      data: { isVerified: true },
    });
  }

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

  async deleteByUserId(userId: string): Promise<number> {
    const result = await this.prisma.mfaChallenge.deleteMany({
      where: { userId },
    });
    return result.count;
  }
}
