import { prisma } from '@/lib/db';
import { companyKnowledgeBaseAdapter } from '@/lib/adapters/whatsapp';
import { logger } from '@/lib/logger';

export async function getKnowledgeBaseEntry(entryId: string) {
  return companyKnowledgeBaseAdapter.findUnique({
    where: { id: entryId },
  });
}

export async function updateKnowledgeBaseEntry(
  entryId: string,
  updates: {
    question?: string;
    answer?: string;
    category?: string | null;
    language?: string;
    isActive?: boolean;
    priority?: number;
  }
) {
  const entry = await companyKnowledgeBaseAdapter.update({
    where: { id: entryId },
    data: {
      ...updates,
      updatedAt: new Date(),
    },
  });
  return entry;
}

export async function deleteKnowledgeBaseEntry(entryId: string) {
  try {
    await companyKnowledgeBaseAdapter.deleteOne({
      where: { id: entryId },
    });
  } catch (error) {
    logger.error('Failed to delete knowledge base entry', { entryId, error });
    throw error;
  }
}

export async function listKnowledgeBaseEntries(filters?: {
  organizationId?: string;
  category?: string;
  language?: string;
  isActive?: boolean;
  limit?: number;
  offset?: number;
}) {
  const { limit = 50, offset = 0, ...whereFilters } = filters || {};

  // Build where clause explicitly to avoid Prisma type spread issues
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const where: any = {};
  if (whereFilters.organizationId) where.organizationId = whereFilters.organizationId;
  if (whereFilters.category) where.category = whereFilters.category;
  if (whereFilters.language) where.language = whereFilters.language;
  if (whereFilters.isActive !== undefined) where.isActive = whereFilters.isActive;

  const [entries, total] = await Promise.all([
    companyKnowledgeBaseAdapter.findMany({
      where,
      orderBy: { priority: 'desc' },
      take: limit,
      skip: offset,
    }),
    companyKnowledgeBaseAdapter.count({ where }),
  ]);
  return { entries, total, limit, offset };
}

export async function createKnowledgeBaseEntry(data: {
  question: string;
  answer: string;
  category?: string | null;
  language?: string;
  isActive?: boolean;
  priority?: number;
  organizationId?: string;
}) {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const entry = await companyKnowledgeBaseAdapter.create({ data: data as any });
  return entry;
}

/**
 * Resolve the org owner's userId from an organizationId.
 * The Gemini RAG store is keyed by userId (org owner).
 */
async function resolveOrgOwnerUserId(organizationId: string): Promise<string | null> {
  const org = await prisma.organizations.findUnique({
    where: { id: organizationId },
    select: { ownerId: true },
  });
  return org?.ownerId ?? null;
}

/**
 * Query the knowledge base using Gemini RAG (uploaded documents) + FAQ table.
 *
 * Called by:
 * - /api/whatsapp/knowledge-base/query (N8N tool endpoint)
 * - WhatsApp AI engine's queryKnowledgeBase()
 *
 * Returns combined results from:
 * 1. Gemini FileSearch RAG (uploaded PDF/Word/text documents)
 * 2. company_knowledge_base FAQ entries (keyword match fallback)
 */
export async function queryKnowledgeBase(
  query: { organizationId: string; query: string; language?: string; limit?: number }
): Promise<Array<{
  source: 'gemini_rag' | 'faq';
  answer?: string;
  question?: string;
  excerpt?: string;
  category?: string | null;
  citations?: Array<{ documentTitle: string; excerpt: string }>;
  metadata?: Record<string, unknown>;
}>> {
  const results: Array<{
    source: 'gemini_rag' | 'faq';
    answer?: string;
    question?: string;
    excerpt?: string;
    category?: string | null;
    citations?: Array<{ documentTitle: string; excerpt: string }>;
    metadata?: Record<string, unknown>;
  }> = [];

  const limit = query.limit ?? 5;

  // 1. Try Gemini RAG (uploaded documents)
  try {
    const { GeminiRAGService } = await import('@/lib/services/gemini-rag.service');

    if (GeminiRAGService.isConfigured()) {
      const userId = await resolveOrgOwnerUserId(query.organizationId);

      if (userId) {
        const stats = await GeminiRAGService.getStoreStats(userId);

        if (stats.hasStore && stats.activeDocumentCount > 0) {
          const ragResult = await GeminiRAGService.queryWithRAG(userId, query.query, {
            language: query.language === 'ar' ? 'ar' : 'en',
            includeCitations: true,
          });

          if (ragResult.success && ragResult.answer) {
            results.push({
              source: 'gemini_rag',
              answer: ragResult.answer,
              citations: ragResult.citations.map((c) => ({
                documentTitle: c.documentTitle,
                excerpt: c.excerpt,
              })),
              metadata: {
                model: ragResult.metadata.model,
                queryTimeMs: ragResult.metadata.queryTimeMs,
                activeDocuments: stats.activeDocumentCount,
              },
            });
          }
        }
      }
    }
  } catch (error) {
    logger.error('Gemini RAG query failed in WhatsApp KB service', { error, organizationId: query.organizationId });
  }

  // 2. Also query company_knowledge_base FAQ entries (keyword match)
  try {
    const keywords = query.query
      .toLowerCase()
      .split(/\s+/)
      .filter((w) => w.length >= 3)
      .slice(0, 10);

    if (keywords.length > 0) {
      const entries = await companyKnowledgeBaseAdapter.findMany({
        where: {
          organizationId: query.organizationId,
          isActive: true,
          OR: keywords.map((keyword) => ({
            question: { contains: keyword, mode: 'insensitive' as const },
          })),
        },
        orderBy: { priority: 'desc' },
        take: limit,
        select: {
          question: true,
          answer: true,
          category: true,
        },
      });

      for (const entry of entries) {
        results.push({
          source: 'faq',
          question: (entry as any).question,
          answer: (entry as any).answer,
          category: (entry as any).category,
        });
      }
    }
  } catch (error) {
    logger.error('FAQ query failed in WhatsApp KB service', { error, organizationId: query.organizationId });
  }

  return results;
}
