/**
 * Knowledge Base Seeder Service
 *
 * Seeds an organization's company_knowledge_base with industry-specific
 * default FAQs at provisioning time. Creates bilingual (EN + AR) entries
 * so the WhatsApp AI agent can answer common customer questions from day one.
 *
 * Usage:
 *   import { seedKnowledgeBase } from '@/lib/services/kb-seeder.service';
 *   await seedKnowledgeBase(organizationId, 'health_care');
 */

import { getDefaultFAQs } from '@/lib/config/sector-default-faqs';
import { companyKnowledgeBaseAdapter } from '@/lib/adapters/whatsapp';
import { logger } from '@/lib/logger';

export interface SeedResult {
  /** Number of FAQ pairs successfully seeded (each pair = 1 EN + 1 AR entry) */
  seeded: number;
  /** Number of FAQ pairs that failed to seed */
  errors: number;
  /** Total FAQ pairs attempted */
  total: number;
}

/**
 * Seed default FAQ entries into an organization's knowledge base.
 *
 * For each FAQ pair the function creates two `company_knowledge_base` rows
 * (one English, one Arabic). Already-populated knowledge bases are left
 * untouched — call `shouldSeed()` first to check.
 *
 * @param organizationId - The organization to seed
 * @param sectorKey      - Sector key from industry-sector-map (e.g. 'health_care')
 * @returns Counts of seeded / errored entries
 */
export async function seedKnowledgeBase(
  organizationId: string,
  sectorKey: string,
): Promise<SeedResult> {
  const faqs = getDefaultFAQs(sectorKey);
  let seeded = 0;
  let errors = 0;

  if (faqs.length === 0) {
    logger.warn('No default FAQs found for sector', { organizationId, sectorKey });
    return { seeded: 0, errors: 0, total: 0 };
  }

  const now = new Date();

  for (const faq of faqs) {
    try {
      // Create English entry
      await companyKnowledgeBaseAdapter.create({
        data: {
          organizationId,
          question: faq.question.en,
          answer: faq.answer.en,
          category: faq.category,
          language: 'en',
          isActive: true,
          priority: 0,
          createdAt: now,
          updatedAt: now,
        },
      });

      // Create Arabic entry
      await companyKnowledgeBaseAdapter.create({
        data: {
          organizationId,
          question: faq.question.ar,
          answer: faq.answer.ar,
          category: faq.category,
          language: 'ar',
          isActive: true,
          priority: 0,
          createdAt: now,
          updatedAt: now,
        },
      });

      seeded++;
    } catch (error) {
      errors++;
      logger.error('Failed to seed FAQ entry', {
        organizationId,
        sectorKey,
        question: faq.question.en,
        error,
      });
    }
  }

  logger.info('KB seeding complete', {
    organizationId,
    sectorKey,
    seeded,
    errors,
    total: faqs.length,
  });

  return { seeded, errors, total: faqs.length };
}

/**
 * Check whether an organization's KB already has entries.
 * Returns `true` when the KB is empty and should be seeded.
 */
export async function shouldSeed(organizationId: string): Promise<boolean> {
  try {
    const count = await companyKnowledgeBaseAdapter.count({
      where: { organizationId },
    });
    return count === 0;
  } catch (error) {
    logger.error('Failed to check KB count', { organizationId, error });
    // Fail open — skip seeding rather than duplicating entries
    return false;
  }
}
