/**
 * Onboarding types and validators
 */

import { z } from 'zod';

// Step IDs for the onboarding flow
export type OnboardingStepId =
  | 'welcome'
  | 'whatsapp'
  | 'voiceAgent'
  | 'knowledgeBase'
  | 'workflows'
  | 'testing';

export const onboardingSteps: OnboardingStepId[] = [
  'welcome',
  'whatsapp',
  'voiceAgent',
  'knowledgeBase',
  'workflows',
  'testing',
];

// WhatsApp connection method
export type WhatsAppMethod = 'meta_api' | 'provisioned' | 'skipped';

// Onboarding progress state
export interface OnboardingProgress {
  id: string;
  userId: string;
  welcomeCompleted: boolean;
  whatsappCompleted: boolean;
  whatsappMethod: WhatsAppMethod | null;
  voiceAgentCompleted: boolean;
  knowledgeBaseCompleted: boolean;
  workflowsCompleted: boolean;
  testingCompleted: boolean;
  startedAt: Date;
  completedAt: Date | null;
  lastStepAt: Date;
  dismissedAt: Date | null;
}

// Computed onboarding status
export interface OnboardingStatus {
  isComplete: boolean;
  currentStep: OnboardingStepId;
  completedSteps: OnboardingStepId[];
  progressPercentage: number;
  shouldShowBanner: boolean;
}

// Voice agent configuration
export interface VoiceAgentConfig {
  languages: ('ar' | 'en' | 'both')[];
  tone: 'professional' | 'friendly' | 'casual';
  customGreeting?: string;
}

// Knowledge base entry for quick FAQ setup
export interface QuickFAQ {
  question: string;
  answer: string;
  category: string;
}

// Workflow activation status
export interface WorkflowActivationStatus {
  workflowId: string;
  featureType: string;
  activated: boolean;
}

// API request/response schemas
export const updateProgressSchema = z.object({
  step: z.enum(['welcome', 'whatsapp', 'voiceAgent', 'knowledgeBase', 'workflows', 'testing']),
  completed: z.boolean().optional(),
  data: z
    .object({
      whatsappMethod: z.enum(['meta_api', 'provisioned', 'skipped']).optional(),
    })
    .optional(),
});

export type UpdateProgressRequest = z.infer<typeof updateProgressSchema>;

export const voiceAgentConfigSchema = z.object({
  languages: z.array(z.enum(['ar', 'en', 'both'])),
  tone: z.enum(['professional', 'friendly', 'casual']),
  customGreeting: z.string().max(500).optional(),
});

export type VoiceAgentConfigRequest = z.infer<typeof voiceAgentConfigSchema>;

export const quickFAQSchema = z.object({
  question: z.string().min(5).max(500),
  answer: z.string().min(10).max(2000),
  category: z.string().min(2).max(100),
});

export type QuickFAQRequest = z.infer<typeof quickFAQSchema>;

// Helper to calculate onboarding status
export function calculateOnboardingStatus(progress: OnboardingProgress): OnboardingStatus {
  const completedSteps: OnboardingStepId[] = [];

  if (progress.welcomeCompleted) completedSteps.push('welcome');
  if (progress.whatsappCompleted) completedSteps.push('whatsapp');
  if (progress.voiceAgentCompleted) completedSteps.push('voiceAgent');
  if (progress.knowledgeBaseCompleted) completedSteps.push('knowledgeBase');
  if (progress.workflowsCompleted) completedSteps.push('workflows');
  if (progress.testingCompleted) completedSteps.push('testing');

  const totalSteps = onboardingSteps.length;
  const progressPercentage = Math.round((completedSteps.length / totalSteps) * 100);
  const isComplete = completedSteps.length === totalSteps || !!progress.completedAt;

  // Find current step (first incomplete step)
  let currentStep: OnboardingStepId = 'welcome';
  for (const step of onboardingSteps) {
    if (!completedSteps.includes(step)) {
      currentStep = step;
      break;
    }
  }

  // Show banner if not complete and not dismissed
  const shouldShowBanner = !isComplete && !progress.dismissedAt;

  return {
    isComplete,
    currentStep,
    completedSteps,
    progressPercentage,
    shouldShowBanner,
  };
}

// Helper to get step display name
export function getStepDisplayName(step: OnboardingStepId, lang: 'ar' | 'en'): string {
  const names: Record<OnboardingStepId, { ar: string; en: string }> = {
    welcome: { ar: 'مرحباً', en: 'Welcome' },
    whatsapp: { ar: 'واتساب', en: 'WhatsApp' },
    voiceAgent: { ar: 'الوكيل الصوتي', en: 'Voice Agent' },
    knowledgeBase: { ar: 'قاعدة المعرفة', en: 'Knowledge Base' },
    workflows: { ar: 'سير العمل', en: 'Workflows' },
    testing: { ar: 'الاختبار', en: 'Testing' },
  };

  return names[step][lang];
}

// Helper to get step number (1-indexed)
export function getStepNumber(step: OnboardingStepId): number {
  return onboardingSteps.indexOf(step) + 1;
}
