/**
 * Organization Provisioning Service
 *
 * Orchestrates post-signup seeding for a newly created organization:
 *  1. Seed sector-specific appointment types
 *  2. Seed knowledge base with industry FAQs
 *  3. Configure AI agent defaults (greetings, model, payment settings)
 *
 * Each step is fault-tolerant — failures in one do not block others.
 * The entire flow is idempotent and safe to call multiple times.
 */

import { seedIndustryDefaults } from "@/lib/services/appointment-type-seeder";
import { seedKnowledgeBase } from "@/lib/services/kb-seeder.service";
import { getSectorForIndustry } from "@/lib/config/industry-sector-map";
import type { SectorKey } from "@/lib/config/industry-sector-map";
import { getSectorConfig } from "@/lib/config/sector-registry";
import type { SectorConfig } from "@/lib/config/sector-registry";
import { convexMutation } from "@/lib/convex-client";
import { CONVEX_PATHS } from "@/lib/convex-paths";
import { logger } from "@/lib/logger";

// ── Types ────────────────────────────────────────────────────────────────

export interface ProvisioningResult {
  organizationId: string;
  industry: string;
  sector: SectorKey;
  appointmentTypesSeeded: boolean;
  kbSeeded: { seeded: number; errors: number } | null;
  workflowsSeeded: { seeded: number; errors: number } | null;
  aiDefaultsConfigured: boolean;
}

// ── AI Defaults ──────────────────────────────────────────────────────────

/**
 * Persist AI agent defaults on the organization record via Convex mutation.
 * Uses the existing `updateOrganizationNoAuth` mutation which now accepts
 * AI-related fields (aiGreetingEn, aiGreetingAr, aiModel, etc.).
 */
async function configureAIDefaults(
  organizationId: string,
  sectorConfig: SectorConfig,
): Promise<void> {
  const sectorNameEn = sectorConfig.displayName.en.toLowerCase();
  const sectorNameAr = sectorConfig.displayName.ar;

  const defaults = {
    organizationId,
    aiGreetingEn: `Welcome to our ${sectorNameEn} services! How can I help you today?`,
    aiGreetingAr: `أهلاً وسهلاً! كيف يمكنني مساعدتك اليوم في خدمات ${sectorNameAr}؟`,
    aiModel: "openrouter/anthropic/claude-sonnet-4",
    depositRequired: sectorConfig.paymentConfig.depositRequired,
    depositPercentage: sectorConfig.paymentConfig.defaultDepositPercentage,
    autoSendPaymentLink: sectorConfig.paymentConfig.autoSendPaymentLink,
  };

  await convexMutation(CONVEX_PATHS.updateOrganizationNoAuth, defaults);

  logger.info("[AI Defaults] Configured", {
    organizationId,
    aiModel: defaults.aiModel,
    depositRequired: defaults.depositRequired,
    depositPercentage: defaults.depositPercentage,
  });
}

// ── Main Orchestrator ────────────────────────────────────────────────────

/**
 * Auto-provision a newly created organization with sector-specific defaults.
 * Called after org creation during signup success.
 *
 * Idempotent — safe to call multiple times (seeders check for existing data).
 */
export async function provisionOrganization(
  organizationId: string,
  ownerId: string,
  industry: string | null | undefined,
): Promise<ProvisioningResult> {
  const sector = getSectorForIndustry(industry);
  const sectorConfig = getSectorConfig(sector);

  logger.info("[Provisioning] Starting org provisioning", {
    organizationId,
    industry,
    sector,
  });

  const result: ProvisioningResult = {
    organizationId,
    industry: industry ?? "unknown",
    sector,
    appointmentTypesSeeded: false,
    kbSeeded: null,
    workflowsSeeded: null,
    aiDefaultsConfigured: false,
  };

  // 1. Seed appointment types
  try {
    await seedIndustryDefaults(ownerId, organizationId, industry);
    result.appointmentTypesSeeded = true;
    logger.info("[Provisioning] Appointment types seeded", {
      organizationId,
    });
  } catch (error) {
    logger.error("[Provisioning] Failed to seed appointment types", {
      organizationId,
      error,
    });
  }

  // 2. Seed knowledge base
  try {
    result.kbSeeded = await seedKnowledgeBase(organizationId, sector);
    logger.info("[Provisioning] KB seeded", {
      organizationId,
      ...result.kbSeeded,
    });
  } catch (error) {
    logger.error("[Provisioning] Failed to seed KB", {
      organizationId,
      error,
    });
  }

  // 2b. Seed default sector workflows for the WhatsApp AI agent
  try {
    const { seedDefaultWorkflows } = await import(
      "@/lib/services/workflow-seeder.service"
    );
    result.workflowsSeeded = await seedDefaultWorkflows(
      organizationId,
      industry,
    );
    logger.info("[Provisioning] Workflows seeded", {
      organizationId,
      ...result.workflowsSeeded,
    });
  } catch (error) {
    logger.error("[Provisioning] Failed to seed workflows", {
      organizationId,
      error,
    });
  }

  // 3. Configure AI agent defaults
  try {
    await configureAIDefaults(organizationId, sectorConfig);
    result.aiDefaultsConfigured = true;
    logger.info("[Provisioning] AI defaults configured", {
      organizationId,
    });
  } catch (error) {
    logger.error("[Provisioning] Failed to configure AI defaults", {
      organizationId,
      error,
    });
  }

  logger.info("[Provisioning] Complete", { organizationId, result });
  return result;
}
