import { createId } from '@paralleldrive/cuid2';
import { prisma } from '@/lib/db';
import {
  getIndustryConfig,
  type IndustryAppointmentType,
} from '@/lib/config/industry-appointment-types';

/**
 * Returns suggested appointment types for an industry,
 * filtered to exclude names the org already has.
 */
export function getSuggestedTypes(
  industry: string | null | undefined,
  existingTypeNames: string[],
): IndustryAppointmentType[] {
  const config = getIndustryConfig(industry);
  const existingLower = new Set(existingTypeNames.map(n => n.toLowerCase()));
  return config.suggested.filter(t => !existingLower.has(t.nameEn.toLowerCase()));
}

/**
 * Seeds core appointment types for an org based on their industry.
 * Uses skipDuplicates so it is safe to call multiple times.
 */
export async function seedIndustryDefaults(
  userId: string,
  organizationId: string,
  industry: string | null | undefined,
): Promise<void> {
  const config = getIndustryConfig(industry);

  const data = config.core.map((type, index) => ({
    id: createId(),
    organizationId,
    nameEn: type.nameEn,
    nameAr: type.nameAr,
    duration: type.duration,
    price: type.price ?? null,
    category: type.category,
    categoryAr: type.categoryAr,
    itemType: type.itemType,
    isActive: true,
    sortOrder: index,
    createdBy: userId,
  }));

  await prisma.appointment_types.createMany({
    data,
    skipDuplicates: true,
  });
}
