/**
 * AppointmentProvisioningService
 *
 * Thin wrapper around the appointment-type-seeder for use during onboarding.
 * Provisions core appointment types for a new organization based on their industry.
 */

import { seedIndustryDefaults } from "@/lib/services/appointment-type-seeder";
import { convexQuery } from "@/lib/convex-client";
import { logger } from "@/lib/logger";

interface ProvisionResult {
  provisioned: boolean;
  organizationId?: string;
  error?: string;
}

export const AppointmentProvisioningService = {
  /**
   * Provisions core appointment types for a user/org based on their industry.
   * Safe to call multiple times — skips duplicates.
   */
  async provisionCoreTypes(
    userId: string,
    industry: string,
    ownerId: string,
  ): Promise<ProvisionResult> {
    try {
      // Try to find the org for this user
      const orgState = await convexQuery<Record<string, unknown>>(
        "organizations/queries:getOrganizationStateByUserId",
        { userId },
      ).catch(() => null);

      const organization = orgState?.organization as
        | Record<string, unknown>
        | undefined;
      const organizationId = (organization?._id ||
        organization?.id) as string | undefined;

      if (!organizationId) {
        logger.warn("[AppointmentProvisioning] No org found, skipping", {
          userId,
          industry,
        });
        return { provisioned: false, error: "No organization found" };
      }

      await seedIndustryDefaults(ownerId, organizationId, industry);

      logger.info("[AppointmentProvisioning] Core types provisioned", {
        userId,
        organizationId,
        industry,
      });

      return { provisioned: true, organizationId };
    } catch (err) {
      const error = err instanceof Error ? err.message : String(err);
      logger.error("[AppointmentProvisioning] Failed", { userId, industry, error });
      return { provisioned: false, error };
    }
  },
};
