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

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

  async createMany(userId: string, knowledgeBaseId: string, sourceId: string, importId: string, candidates: Array<{
    title: string;
    summary?: string;
    content?: string;
    tagsJson?: any;
    recallQuestionsJson?: any;
    sourceTextSnippet?: string;
    sourceChunkIds?: any;
    confidence?: number;
    difficulty?: string;
    orderIndex?: number;
  }>) {
    const data = candidates.map((c, i) => ({
      userId,
      knowledgeBaseId,
      sourceId,
      importId,
      title: c.title,
      summary: c.summary,
      content: c.content,
      tagsJson: c.tagsJson,
      recallQuestionsJson: c.recallQuestionsJson,
      sourceTextSnippet: c.sourceTextSnippet,
      sourceChunkIds: c.sourceChunkIds,
      confidence: c.confidence ?? 0,
      difficulty: c.difficulty,
      orderIndex: c.orderIndex ?? i,
      status: 'PENDING',
    }));
    return this.prisma.importCandidate.createMany({ data });
  }

  async findBySource(sourceId: string) {
    return this.prisma.importCandidate.findMany({
      where: { sourceId },
      orderBy: { orderIndex: 'asc' },
    });
  }

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

  async updateStatus(id: string, status: string) {
    return this.prisma.importCandidate.update({
      where: { id },
      data: { status },
    });
  }

  async batchAccept(ids: string[]) {
    return this.prisma.importCandidate.updateMany({
      where: { id: { in: ids } },
      data: { status: 'ACCEPTED' },
    });
  }

  async update(id: string, data: { title?: string; summary?: string; content?: string; tagsJson?: any; recallQuestionsJson?: any }) {
    return this.prisma.importCandidate.update({
      where: { id },
      data: { ...data, status: 'EDITED' },
    });
  }
}
