import { prisma } from '../database';

export class KnowledgeBaseService {
  public async list(guildId: string) {
    return prisma.knowledgeBaseArticle.findMany({ where: { guildId }, orderBy: { createdAt: 'asc' } });
  }

  public async save(article: { id?: string; guildId: string; title: string; keywords: string[]; content: string }) {
    const data = {
      guildId: article.guildId,
      title: article.title,
      keywords: article.keywords,
      content: article.content
    };
    if (article.id) {
      return prisma.knowledgeBaseArticle.update({ where: { id: article.id }, data });
    }
    return prisma.knowledgeBaseArticle.create({ data });
  }

  public async remove(guildId: string, id: string) {
    const found = await prisma.knowledgeBaseArticle.findFirst({ where: { id, guildId } });
    if (!found) return false;
    await prisma.knowledgeBaseArticle.delete({ where: { id } });
    return true;
  }

  public async match(guildId: string, text: string) {
    if (!text) return [];
    const lowered = text.toLowerCase();
    const articles = await prisma.knowledgeBaseArticle.findMany({ where: { guildId }, take: 50 });
    return articles.filter((a) => (a.keywords || []).some((k) => lowered.includes(k.toLowerCase()))).slice(0, 3);
  }
}
