/**
 * Workflow Seeder Service
 *
 * Seeds default sector-specific WhatsApp workflows for a newly provisioned
 * organization. Called from `org-provisioning.service.ts` after the KB seeder.
 *
 * Idempotency: this seeder always inserts. It is the caller's responsibility
 * to ensure provisioning runs once per org. Soft-deletes via `deleteWorkflow`
 * keep historical rows around, so re-running would create duplicates.
 */

import { convexMutation } from "@/lib/convex-client";
import { logger } from "@/lib/logger";
import { getDefaultWorkflows } from "@/lib/config/sector-default-workflows";
import {
  getSectorForIndustry,
  type SectorKey,
} from "@/lib/config/industry-sector-map";

export async function seedDefaultWorkflows(
  organizationId: string,
  industry: string | null | undefined,
): Promise<{ seeded: number; errors: number }> {
  const sector: SectorKey = getSectorForIndustry(industry);
  const defaults = getDefaultWorkflows(sector);

  let seeded = 0;
  let errors = 0;
  const now = Date.now();

  for (const wf of defaults) {
    try {
      await convexMutation("whatsapp/workflows:createWorkflow", {
        organizationId,
        name: wf.name,
        description: wf.description,
        sector,
        triggerKeywords: wf.triggerKeywords,
        triggerIntent: wf.triggerIntent,
        systemPromptAddition: wf.systemPromptAddition,
        collectFields: wf.collectFields,
        confirmationMessageEn: wf.confirmationMessageEn,
        confirmationMessageAr: wf.confirmationMessageAr,
        isActive: true,
        priority: wf.priority,
        language: wf.language,
        createdAt: now,
        updatedAt: now,
      });
      seeded++;
    } catch (error) {
      errors++;
      logger.error("[WorkflowSeeder] Failed to seed workflow", {
        organizationId,
        name: wf.name,
        error,
      });
    }
  }

  logger.info("[WorkflowSeeder] Complete", {
    organizationId,
    sector,
    seeded,
    errors,
  });
  return { seeded, errors };
}
