/**
 * Sector Configuration Registry
 *
 * Unified per-sector configuration for the WhatsApp conversation engine.
 * Combines display names, AI context, field definitions, payment config,
 * and post-booking actions into a single SectorConfig per sector.
 *
 * Usage:
 *   import { getSectorConfig } from '@/lib/config/sector-registry';
 *   const config = getSectorConfig('health_care');
 */

import type { SectorAIContext } from "@/lib/config/sector-ai-context";
import { SECTOR_AI_CONTEXTS } from "@/lib/config/sector-ai-context";
import type { SectorKey } from "@/lib/config/industry-sector-map";
import {
  SECTOR_KEYS,
  SECTOR_DISPLAY_NAMES,
  getSectorForIndustry,
} from "@/lib/config/industry-sector-map";

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

/** Field definition for sector-specific data collection */
export interface FieldDef {
  key: string;
  label: { en: string; ar: string };
  required: boolean;
  type: "text" | "date" | "time" | "number" | "select";
}

/** Payment configuration per sector */
export interface PaymentConfig {
  depositRequired: boolean;
  /** Percentage of total to collect as deposit (0-100) */
  defaultDepositPercentage: number;
  autoSendPaymentLink: boolean;
}

/** Post-booking action types */
export type PostBookingActionType =
  | "send_confirmation"
  | "request_review"
  | "send_reminder"
  | "send_instructions"
  | "send_documents";

/** A single post-booking action to execute */
export interface PostBookingAction {
  type: PostBookingActionType;
  /** Minutes after booking. 0 = immediate. Negative = before appointment. */
  delayMinutes: number;
  templateKey?: string;
}

/** Cancellation / refund policy applied when a customer cancels via WhatsApp. */
export interface CancellationPolicy {
  /** Full-refund window: cancel at least this many hours before appointment → full refund. */
  fullRefundHours: number;
  /** Future: partial-refund tier — not used in v1, keep set to 0. */
  partialRefundHours: number;
  /** Future: percent refunded in the partial window (0-100). */
  partialRefundPercent: number;
}

/** Full sector configuration */
export interface SectorConfig {
  key: SectorKey;
  displayName: { en: string; ar: string };
  transactionNoun: { en: string; ar: string };
  aiContext: SectorAIContext;
  /**
   * Sector-specific fields beyond the core set (name, service, date, time).
   * All marked as optional by default.
   */
  extraFields: FieldDef[];
  paymentConfig: PaymentConfig;
  /** Cancellation / refund policy applied when a customer cancels via WhatsApp. */
  cancellationPolicy?: CancellationPolicy;
  postBookingActions: PostBookingAction[];
}

// ── Field Definitions Lookup ──────────────────────────────────────────────

const FIELD_DEFS: Record<string, Omit<FieldDef, "required">> = {
  doctor_specialist: {
    key: "doctor_specialist",
    label: { en: "Doctor/Specialist", ar: "الطبيب/الأخصائي" },
    type: "text",
  },
  department: {
    key: "department",
    label: { en: "Department", ar: "القسم" },
    type: "text",
  },
  stylist_therapist: {
    key: "stylist_therapist",
    label: { en: "Stylist/Therapist", ar: "المصفف/المعالج" },
    type: "text",
  },
  treatment_area: {
    key: "treatment_area",
    label: { en: "Treatment Area", ar: "منطقة العلاج" },
    type: "text",
  },
  party_size: {
    key: "party_size",
    label: { en: "Party Size", ar: "عدد الأشخاص" },
    type: "number",
  },
  dietary_requirements: {
    key: "dietary_requirements",
    label: { en: "Dietary Requirements", ar: "المتطلبات الغذائية" },
    type: "text",
  },
  special_occasion: {
    key: "special_occasion",
    label: { en: "Special Occasion", ar: "مناسبة خاصة" },
    type: "text",
  },
  consultant: {
    key: "consultant",
    label: { en: "Consultant", ar: "المستشار" },
    type: "text",
  },
  service_category: {
    key: "service_category",
    label: { en: "Service Category", ar: "فئة الخدمة" },
    type: "text",
  },
  property_address: {
    key: "property_address",
    label: { en: "Property Address", ar: "عنوان العقار" },
    type: "text",
  },
  property_type: {
    key: "property_type",
    label: { en: "Property Type", ar: "نوع العقار" },
    type: "select",
  },
  bedrooms: {
    key: "bedrooms",
    label: { en: "Bedrooms", ar: "غرف النوم" },
    type: "number",
  },
  vehicle_type: {
    key: "vehicle_type",
    label: { en: "Vehicle Type", ar: "نوع المركبة" },
    type: "select",
  },
  pickup_location: {
    key: "pickup_location",
    label: { en: "Pickup Location", ar: "موقع الاستلام" },
    type: "text",
  },
  return_date: {
    key: "return_date",
    label: { en: "Return Date", ar: "تاريخ الإرجاع" },
    type: "date",
  },
  service_address: {
    key: "service_address",
    label: { en: "Service Address", ar: "عنوان الخدمة" },
    type: "text",
  },
  issue_description: {
    key: "issue_description",
    label: { en: "Issue Description", ar: "وصف المشكلة" },
    type: "text",
  },
  course_subject: {
    key: "course_subject",
    label: { en: "Course/Subject", ar: "الدورة/المادة" },
    type: "text",
  },
  level: {
    key: "level",
    label: { en: "Level", ar: "المستوى" },
    type: "select",
  },
  event_type: {
    key: "event_type",
    label: { en: "Event Type", ar: "نوع الفعالية" },
    type: "text",
  },
  guest_count: {
    key: "guest_count",
    label: { en: "Guest Count", ar: "عدد الضيوف" },
    type: "number",
  },
  venue_preference: {
    key: "venue_preference",
    label: { en: "Venue Preference", ar: "تفضيل المكان" },
    type: "select",
  },
  pet_type: {
    key: "pet_type",
    label: { en: "Pet Type", ar: "نوع الحيوان" },
    type: "text",
  },
  pet_name: {
    key: "pet_name",
    label: { en: "Pet Name", ar: "اسم الحيوان" },
    type: "text",
  },
  pet_weight: {
    key: "pet_weight",
    label: { en: "Pet Weight (kg)", ar: "وزن الحيوان (كجم)" },
    type: "number",
  },
  program_name: {
    key: "program_name",
    label: { en: "Program Name", ar: "اسم البرنامج" },
    type: "text",
  },
  participant_count: {
    key: "participant_count",
    label: { en: "Participant Count", ar: "عدد المشاركين" },
    type: "number",
  },
  service_type: {
    key: "service_type",
    label: { en: "Service Type", ar: "نوع الخدمة" },
    type: "text",
  },
  reference_number: {
    key: "reference_number",
    label: { en: "Reference Number", ar: "الرقم المرجعي" },
    type: "text",
  },
};

// ── Helpers ───────────────────────────────────────────────────────────────

/** Convert string field keys from SectorAIContext into typed FieldDef objects */
function resolveExtraFields(fieldKeys: string[]): FieldDef[] {
  return fieldKeys
    .map((key) => {
      const def = FIELD_DEFS[key];
      if (!def) return null;
      return { ...def, required: false };
    })
    .filter((f): f is FieldDef => f !== null);
}

/** Standard post-booking actions applied to all sectors */
const BASE_POST_BOOKING_ACTIONS: PostBookingAction[] = [
  { type: "send_confirmation", delayMinutes: 0 },
  { type: "send_reminder", delayMinutes: -1440 },
  { type: "request_review", delayMinutes: 60 },
];

// ── Payment Configs ───────────────────────────────────────────────────────

const PAYMENT_CONFIGS: Record<SectorKey, PaymentConfig> = {
  health_care: {
    depositRequired: true,
    defaultDepositPercentage: 0,
    autoSendPaymentLink: true,
  },
  beauty_wellness: {
    depositRequired: true,
    defaultDepositPercentage: 50,
    autoSendPaymentLink: true,
  },
  food_hospitality: {
    depositRequired: false,
    defaultDepositPercentage: 0,
    autoSendPaymentLink: false,
  },
  retail_services: {
    depositRequired: true,
    defaultDepositPercentage: 30,
    autoSendPaymentLink: true,
  },
  property_facilities: {
    depositRequired: false,
    defaultDepositPercentage: 0,
    autoSendPaymentLink: false,
  },
  mobility_automotive: {
    depositRequired: true,
    defaultDepositPercentage: 50,
    autoSendPaymentLink: true,
  },
  home_services_trades: {
    depositRequired: true,
    defaultDepositPercentage: 30,
    autoSendPaymentLink: true,
  },
  education: {
    depositRequired: true,
    defaultDepositPercentage: 100,
    autoSendPaymentLink: true,
  },
  events_venues: {
    depositRequired: true,
    defaultDepositPercentage: 50,
    autoSendPaymentLink: true,
  },
  pet_services: {
    depositRequired: true,
    defaultDepositPercentage: 25,
    autoSendPaymentLink: true,
  },
  nonprofit_community: {
    depositRequired: false,
    defaultDepositPercentage: 0,
    autoSendPaymentLink: false,
  },
  public_sector: {
    depositRequired: false,
    defaultDepositPercentage: 0,
    autoSendPaymentLink: false,
  },
};

// ── Cancellation Policies ─────────────────────────────────────────────────

/**
 * Default full-refund window applied to any sector without a specific override.
 * Matches the v1 spec: 4 hours before appointment for full refund.
 */
const DEFAULT_CANCELLATION_POLICY: CancellationPolicy = {
  fullRefundHours: 4,
  partialRefundHours: 0,
  partialRefundPercent: 0,
};

/**
 * Per-sector cancellation policy overrides. Sectors not listed here inherit
 * `DEFAULT_CANCELLATION_POLICY`. Lookup happens in `buildSectorConfig` so
 * every sector in `SECTOR_REGISTRY` is guaranteed to have a `cancellationPolicy`.
 */
const CANCELLATION_POLICIES: Partial<Record<SectorKey, CancellationPolicy>> = {
  health_care: {
    fullRefundHours: 4,
    partialRefundHours: 0,
    partialRefundPercent: 0,
  },
  beauty_wellness: {
    fullRefundHours: 4,
    partialRefundHours: 0,
    partialRefundPercent: 0,
  },
  food_hospitality: {
    fullRefundHours: 2,
    partialRefundHours: 0,
    partialRefundPercent: 0,
  },
  education: {
    fullRefundHours: 24,
    partialRefundHours: 0,
    partialRefundPercent: 0,
  },
};

/** Sector-specific extra post-booking actions beyond the base set */
const EXTRA_POST_BOOKING_ACTIONS: Partial<
  Record<SectorKey, PostBookingAction[]>
> = {
  health_care: [
    {
      type: "send_instructions",
      delayMinutes: -120,
      templateKey: "pre_visit_instructions",
    },
  ],
  beauty_wellness: [
    {
      type: "send_instructions",
      delayMinutes: -60,
      templateKey: "preparation_tips",
    },
  ],
  property_facilities: [
    {
      type: "send_documents",
      delayMinutes: 0,
      templateKey: "property_documents",
    },
  ],
  events_venues: [
    {
      type: "send_documents",
      delayMinutes: 0,
      templateKey: "event_details",
    },
  ],
};

// ── Registry ──────────────────────────────────────────────────────────────

function buildSectorConfig(key: SectorKey): SectorConfig {
  const aiContext = SECTOR_AI_CONTEXTS[key];
  const displayName = SECTOR_DISPLAY_NAMES[key];
  const extraActions = EXTRA_POST_BOOKING_ACTIONS[key] ?? [];
  const cancellationPolicy =
    CANCELLATION_POLICIES[key] ?? DEFAULT_CANCELLATION_POLICY;

  return {
    key,
    displayName,
    transactionNoun: aiContext.transactionNoun,
    aiContext,
    extraFields: resolveExtraFields(aiContext.extraFieldsToCollect),
    paymentConfig: PAYMENT_CONFIGS[key],
    cancellationPolicy,
    postBookingActions: [...BASE_POST_BOOKING_ACTIONS, ...extraActions],
  };
}

export const SECTOR_REGISTRY: Record<SectorKey, SectorConfig> =
  SECTOR_KEYS.reduce(
    (acc, key) => {
      acc[key] = buildSectorConfig(key);
      return acc;
    },
    {} as Record<SectorKey, SectorConfig>,
  );

// ── Public API ────────────────────────────────────────────────────────────

/**
 * Get the full sector configuration for a given sector key.
 * Falls back to `retail_services` for unknown keys.
 */
export function getSectorConfig(sectorKey: SectorKey): SectorConfig {
  return SECTOR_REGISTRY[sectorKey] ?? SECTOR_REGISTRY.retail_services;
}

/**
 * Get the sector configuration for an industry key (e.g. from onboarding).
 * Resolves the industry to its parent sector, then returns the config.
 */
export function getSectorConfigForIndustry(industryKey: string): SectorConfig {
  const sectorKey = getSectorForIndustry(industryKey);
  return getSectorConfig(sectorKey);
}
