import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../infrastructure/database/prisma.service';

@Injectable()
export class ReviewRepository {
  constructor(private readonly prisma: PrismaService) {}

  async findById(id: string) {
    return this.prisma.reviewCard.findUnique({ where: { id } });
  }

  async findDueCards(userId: string) {
    return this.prisma.reviewCard.findMany({
      where: {
        userId,
        status: 'active',
        nextReviewAt: { lte: new Date() },
        deletedAt: null,
      },
      orderBy: { nextReviewAt: 'asc' },
    });
  }

  async insertCard(data: {
    userId: string;
    knowledgeItemId?: string;
    frontText: string;
    backText?: string;
    difficulty?: string;
    status?: string;
    intervalDays?: number;
    easeFactor?: number;
    repetitionCount?: number;
    lapseCount?: number;
    scheduleState?: string;
    nextReviewAt?: Date;
  }) {
    return this.prisma.reviewCard.create({ data });
  }

  async updateCard(id: string, data: {
    status?: string;
    nextReviewAt?: Date;
    intervalDays?: number;
    easeFactor?: number;
    repetitionCount?: number;
    lapseCount?: number;
    scheduleState?: string;
  }) {
    await this.prisma.reviewCard.update({ where: { id }, data });
  }

  async insertLog(data: {
    userId: string;
    reviewCardId: string;
    rating: string;
    responseText?: string;
  }) {
    return this.prisma.reviewLog.create({
      data: {
        ...data,
        reviewedAt: new Date(),
      },
    });
  }
}
