/**
 * PostHog Analytics Event Taxonomy & Types
 * 
 * Strict, typed definitions for all business and product analytics events across:
 * - Authentication & Onboarding
 * - Agent & Agency Verification (KYC)
 * - Marketplace & Property Operations
 * - Search & Filter Discovery
 * - Lead Generation & Agent Contacts
 * - Subscriptions, Checkout & Paystack Payments
 */

export const ANALYTICS_EVENTS = {
  // 1. Auth & Onboarding
  USER_SIGNED_UP: "user_signed_up",
  ACCOUNT_TYPE_SELECTED: "account_type_selected",
  PROFILE_COMPLETED: "profile_completed",

  // 2. Verification (KYC)
  VERIFICATION_STARTED: "verification_started",
  DOCUMENT_UPLOADED: "document_uploaded",
  VERIFICATION_SUBMITTED: "verification_submitted",
  VERIFICATION_NEEDS_ACTION: "verification_needs_action",
  VERIFICATION_APPROVED: "verification_approved",

  // 3. Marketplace & Properties
  PROPERTY_CREATED: "property_created",
  PROPERTY_SUBMITTED: "property_submitted",
  PROPERTY_PUBLISHED: "property_published",
  PROPERTY_VIEWED: "property_viewed",
  PROPERTY_SAVED: "property_saved",

  // 4. Search & Discovery
  SEARCH_PERFORMED: "search_performed",
  FILTER_APPLIED: "filter_applied",

  // 5. Leads & Contacts
  AGENT_CONTACTED: "agent_contacted",
  WHATSAPP_CLICKED: "whatsapp_clicked",
  PHONE_CONTACT_CLICKED: "phone_contact_clicked",
  VIEWING_REQUESTED: "viewing_requested",

  // 6. Payments & Subscriptions
  PLAN_SELECTED: "plan_selected",
  CHECKOUT_STARTED: "checkout_started",
  PAYMENT_SUCCESSFUL: "payment_successful",
  PAYMENT_FAILED: "payment_failed",
} as const;

export type AnalyticsEventName = (typeof ANALYTICS_EVENTS)[keyof typeof ANALYTICS_EVENTS];

// Event Payload Interfaces

export interface UserSignedUpProps {
  account_type?: string;
  auth_provider?: string;
}

export interface AccountTypeSelectedProps {
  account_type: string;
  previous_type?: string;
}

export interface ProfileCompletedProps {
  account_type?: string;
  state_id?: string | number;
  has_phone?: boolean;
}

export interface VerificationStartedProps {
  step?: number;
  account_type?: string;
}

export interface DocumentUploadedProps {
  document_type: string; // e.g. "NIN_CARD", "DRIVERS_LICENSE", "CAC_CERTIFICATE", "MEMBERSHIP_ID"
  step?: number;
}

export interface VerificationSubmittedProps {
  account_type?: string;
  state_id?: string | number;
  plan_id?: string;
  billing_interval?: string;
}

export interface VerificationNeedsActionProps {
  user_id?: string;
  action_required_field?: string | null;
  reason_category?: string;
}

export interface VerificationApprovedProps {
  user_id?: string;
  account_type?: string;
  plan_id?: string;
  duration_seconds?: number;
}

export interface PropertyCreatedProps {
  property_id: string;
  property_type: string;
  listing_type: string;
  state_id?: string | number;
  price?: number;
  currency?: string;
  is_agency?: boolean;
}

export interface PropertySubmittedProps {
  property_id: string;
  property_type: string;
  listing_type: string;
  state_id?: string | number;
  price?: number;
  title_type?: string;
}

export interface PropertyPublishedProps {
  property_id: string;
  property_type?: string;
  listing_type?: string;
  state_id?: string | number;
  price?: number;
  moderation_latency_minutes?: number;
}

export interface PropertyViewedProps {
  property_id: string;
  property_slug?: string;
  property_type?: string;
  listing_type?: string;
  state_id?: string | number;
  price?: number;
  is_verified?: boolean;
}

export interface PropertySavedProps {
  property_id: string;
  property_type?: string;
  listing_type?: string;
  price?: number;
}

export interface SearchPerformedProps {
  query_term?: string;
  state_id?: string | number;
  listing_type?: string;
  property_type?: string;
  has_filters?: boolean;
  results_count?: number;
}

export interface FilterAppliedProps {
  filter_name: string; // e.g. "bedrooms", "max_price", "title_type"
  filter_value: string | number | boolean;
}

export interface AgentContactedProps {
  property_id: string;
  channel?: "FORM" | "MODAL";
  inquiry_type?: string;
}

export interface WhatsAppClickedProps {
  property_id: string;
  channel?: "WHATSAPP";
}

export interface PhoneContactClickedProps {
  property_id: string;
  channel?: "CALL";
}

export interface ViewingRequestedProps {
  property_id: string;
  meeting_type?: "PHYSICAL" | "VIRTUAL_VIDEO";
  has_preferred_date?: boolean;
}

export interface PlanSelectedProps {
  plan_id: string;
  billing_interval?: string;
  price_ngn?: number;
}

export interface CheckoutStartedProps {
  plan_id: string;
  billing_interval?: string;
  amount_ngn?: number;
  currency?: string;
  is_upgrade?: boolean;
}

export interface PaymentSuccessfulProps {
  reference: string;
  plan_id?: string;
  billing_interval?: string;
  amount_ngn?: number;
  currency?: string;
  channel?: string;
  agency_id?: string | null;
}

export interface PaymentFailedProps {
  reference: string;
  plan_id?: string;
  error_code?: string;
  reason?: string;
}

export interface UserTraits {
  user_role?: string;
  roles?: string[];
  account_type?: string;
  plan_id?: string;
  verification_status?: string;
  is_verified?: boolean;
  agency_id?: string | null;
  created_at?: string;
  [key: string]: any;
}

/**
 * List of forbidden keys that must never be sent to PostHog under any circumstances.
 */
export const FORBIDDEN_TRAIT_PATTERNS = [
  /password/i,
  /secret/i,
  /token/i,
  /jwt/i,
  /cookie/i,
  /nin/i,
  /bvn/i,
  /card.*number/i,
  /cvv/i,
  /private_key/i,
  /document_url/i,
  /passport.*url/i,
  /proof_document_url/i,
  /street_address/i,
];

/**
 * Strips any sensitive PII and unauthorized fields from user or event properties
 */
export function sanitizeTraits(traits?: Record<string, any>): Record<string, any> {
  if (!traits || typeof traits !== "object") return {};

  const clean: Record<string, any> = {};

  for (const [key, val] of Object.entries(traits)) {
    if (val === undefined || val === null) continue;

    // Check if key matches forbidden sensitive pattern
    const isForbidden = FORBIDDEN_TRAIT_PATTERNS.some((pattern) => pattern.test(key));
    if (isForbidden) {
      continue;
    }

    // Primitive safety check
    if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
      clean[key] = val;
    } else if (Array.isArray(val)) {
      clean[key] = val.filter((item) => typeof item === "string" || typeof item === "number");
    } else if (typeof val === "object") {
      // Recurse for shallow objects
      clean[key] = sanitizeTraits(val);
    }
  }

  return clean;
}
