import { z } from 'zod';

// =============================================================================
// Knowledge Base Schemas
// =============================================================================

export const KnowledgeBaseUpdateSchema = z.object({
  id: z.string().min(1, 'ID is required'),
  question: z.string().min(1).optional(),
  answer: z.string().min(1).optional(),
  category: z.string().max(100).optional().nullable(),
  language: z.enum(['en', 'ar']).optional(),
  isActive: z.boolean().optional(),
  priority: z.number().int().min(0).max(100).optional(),
});

export type KnowledgeBaseUpdateInput = z.infer<typeof KnowledgeBaseUpdateSchema>;

// =============================================================================
// Language Preference Schemas (for n8n WhatsApp AI Agent)
// =============================================================================

/**
 * Schema for GET /api/whatsapp/language-preference
 * Validates query parameters for retrieving language preference
 */
export const LanguagePreferenceGetSchema = z.object({
  organizationId: z.string().min(1, 'Organization ID is required'),
  phone: z.string().min(5, 'Valid phone number is required'),
});

export type LanguagePreferenceGetInput = z.infer<typeof LanguagePreferenceGetSchema>;

/**
 * Schema for POST /api/whatsapp/language-preference
 * Validates request body for setting language preference
 */
export const LanguagePreferenceSetSchema = z.object({
  organizationId: z.string().min(1, 'Organization ID is required'),
  phone: z.string().min(5, 'Valid phone number is required'),
  language: z.enum(['en', 'ar'], {
    errorMap: () => ({ message: "Language must be 'en' (English) or 'ar' (Arabic)" }),
  }),
});

export type LanguagePreferenceSetInput = z.infer<typeof LanguagePreferenceSetSchema>;

// =============================================================================
// Booking Action Schemas (for n8n AI Agent booking management)
// =============================================================================

/**
 * Customer information for booking creation
 */
export const BookingCustomerSchema = z.object({
  name: z.string().min(1, 'Customer name is required').max(200),
  phone: z.string().min(5, 'Valid phone number is required').max(20),
  email: z.string().email('Invalid email format').optional().nullable(),
});

/**
 * Booking details for creation
 */
export const BookingDetailsSchema = z.object({
  service: z.string().min(1, 'Service name is required').max(200),
  date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be YYYY-MM-DD format'),
  time: z.string().regex(/^\d{2}:\d{2}$/, 'Time must be HH:MM format'),
  duration: z.number().min(15).max(480).default(30),
  staff_member: z.string().max(200).optional().nullable(),
  notes: z.string().max(1000).optional().nullable(),
  total_amount: z.number().min(0).optional().default(0),
  deposit_amount: z.number().min(0).optional().nullable(),
  deposit_required: z.boolean().default(false),
});

/**
 * Schema for POST /api/n8n/booking-action
 * Unified endpoint for all booking management actions
 *
 * Extended to support: create, reschedule, cancel, generate_payment_link, refund, mark_paid, check_status
 */
export const BookingActionSchema = z.object({
  auth_token: z.string().min(1, 'Auth token is required'),
  booking_id: z.string().optional().nullable(), // Optional for create action
  action: z.enum([
    'create',
    'reschedule',
    'cancel',
    'generate_payment_link',
    'refund',
    'mark_paid',
    'check_status',
  ], {
    errorMap: () => ({
      message: "Action must be one of: create, reschedule, cancel, generate_payment_link, refund, mark_paid, check_status",
    }),
  }),
  params: z
    .object({
      // For create action
      user_id: z.string().optional(),
      organization_id: z.string().optional().nullable(),
      conversation_id: z.string().optional().nullable(),
      source: z.enum(['whatsapp', 'voice', 'web', 'phone_call', 'manual']).optional(),
      customer: BookingCustomerSchema.optional(),
      booking: BookingDetailsSchema.optional(),
      // For reschedule action
      newDate: z
        .string()
        .regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be YYYY-MM-DD format')
        .optional(),
      newTime: z
        .string()
        .regex(/^\d{2}:\d{2}$/, 'Time must be HH:MM format')
        .optional(),
      // For cancel and refund actions
      reason: z.string().max(500).optional(),
      refund_reason: z.string().max(500).optional(),
      // For mark_paid action
      payment_reference: z.string().max(200).optional(),
      payment_method: z.enum(['cash', 'bank_transfer', 'card', 'other']).optional(),
    })
    .optional()
    .default({}),
});

export type BookingActionInput = z.infer<typeof BookingActionSchema>;
export type BookingCustomerInput = z.infer<typeof BookingCustomerSchema>;
export type BookingDetailsInput = z.infer<typeof BookingDetailsSchema>;

/**
 * Schema for refund eligibility check
 */
export const RefundEligibilitySchema = z.object({
  auth_token: z.string().min(1, 'Auth token is required'),
  booking_id: z.string().min(1, 'Booking ID is required'),
});

export type RefundEligibilityInput = z.infer<typeof RefundEligibilitySchema>;

// =============================================================================
// Twilio WhatsApp Validators
// =============================================================================

export const TwilioIncomingMessageSchema = z.object({
  MessageSid: z.string().min(1, 'MessageSid is required'),
  From: z.string().startsWith('whatsapp:', 'From must start with whatsapp:'),
  To: z.string().startsWith('whatsapp:', 'To must start with whatsapp:'),
  Body: z.string().max(10000).default(''),
  NumMedia: z.coerce.number().int().min(0).default(0),
  ProfileName: z.string().optional(),
});

export const AIEngineResponseSchema = z.object({
  intent: z.enum([
    'company_query', 'booking_request', 'amend_appointment',
    'check_status', 'greeting', 'general', 'off_topic', 'abuse',
  ]),
  response: z.string().max(2000),
  language: z.enum(['en', 'ar']),
  action: z.object({
    type: z.enum([
      'search_kb', 'create_booking', 'reschedule', 'cancel',
      'generate_payment_link', 'check_status', 'none',
    ]),
    params: z.record(z.unknown()).optional(),
  }).optional(),
  collectedInfo: z.object({
    name: z.string().optional(),
    email: z.string().email().optional(),
    phone: z.string().optional(),
    service: z.string().optional(),
    date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be YYYY-MM-DD').optional(),
    time: z.string().regex(/^\d{2}:\d{2}$/, 'Time must be HH:MM').optional(),
    depositChoice: z.boolean().optional(),
  }).optional(),
  missingFields: z.array(z.string()).optional(),
  guardrailTriggered: z.boolean().optional(),
  guardrailReason: z.string().optional(),
});

export const TwilioKeysConfigSchema = z.object({
  accountSid: z.string().startsWith('AC', 'Account SID must start with AC').min(34).max(34),
  authToken: z.string().min(32, 'Auth token must be at least 32 characters'),
  whatsappNumber: z.string().regex(/^\+\d{10,15}$/, 'Must be E.164 format: +1234567890'),
});

export const N8NAIAgentRequestSchema = z.object({
  auth_token: z.string().min(1, 'Auth token is required'),
  organization_id: z.string().min(1, 'Organization ID is required'),
  customer_phone: z.string().min(5, 'Customer phone is required'),
  message: z.string().min(1).max(10000, 'Message too long'),
  language: z.enum(['en', 'ar']).optional().default('en'),
});

export type TwilioIncomingMessageInput = z.infer<typeof TwilioIncomingMessageSchema>;
export type AIEngineResponseInput = z.infer<typeof AIEngineResponseSchema>;
export type TwilioKeysConfigInput = z.infer<typeof TwilioKeysConfigSchema>;
export type N8NAIAgentRequestInput = z.infer<typeof N8NAIAgentRequestSchema>;

// =============================================================================
// WhatsApp Conversation List Schemas
// =============================================================================

export const ConversationListQuerySchema = z.object({
  organizationId: z.string().min(1, 'Organization ID is required'),
  language: z.enum(['en', 'ar']).optional().nullable(),
  status: z.enum(['active', 'closed', 'archived']).optional().nullable(),
  limit: z.coerce.number().int().min(1).max(100).optional().default(20),
  offset: z.coerce.number().int().min(0).optional().default(0),
});

export type ConversationListQueryInput = z.infer<typeof ConversationListQuerySchema>;

// =============================================================================
// WhatsApp Conversation Logging Schemas
// =============================================================================

export const ConversationLogMessageSchema = z.object({
  role: z.enum(['user', 'assistant', 'system']),
  content: z.string().min(1).max(10000),
  language: z.enum(['en', 'ar']).optional(),
  intent: z.string().optional(),
  toolsUsed: z.array(z.string()).optional(),
  metadata: z.record(z.unknown()).optional(),
});

export const ConversationLogSchema = z.object({
  organizationId: z.string().min(1, 'Organization ID is required'),
  userPhone: z.string().min(5, 'Valid phone number is required'),
  userName: z.string().optional().nullable(),
  language: z.enum(['en', 'ar']).optional().default('en'),
  messages: z.array(ConversationLogMessageSchema).min(1, 'At least one message is required'),
});

export type ConversationLogInput = z.infer<typeof ConversationLogSchema>;

// =============================================================================
// WhatsApp Booking Creation Schema
// =============================================================================

export const BookingCreateSchema = z.object({
  organizationId: z.string().min(1, 'Organization ID is required'),
  customer: BookingCustomerSchema,
  service: z.string().min(1, 'Service name is required'),
  date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'Date must be YYYY-MM-DD'),
  time: z.string().regex(/^\d{2}:\d{2}$/, 'Time must be HH:MM'),
  duration: z.number().min(15).max(480).default(30),
  staffId: z.string().optional(),
  notes: z.string().max(1000).optional(),
  source: z.enum(['whatsapp', 'voice', 'web']).default('whatsapp'),
  conversationId: z.string().optional(),
});

export type BookingCreateInput = z.infer<typeof BookingCreateSchema>;

// Knowledge Base Query Schema
export const KnowledgeBaseQuerySchema = z.object({
  query: z.string().min(1).max(1000),
  language: z.enum(['ar', 'en']).default('ar'),
  limit: z.number().int().min(1).max(20).default(5),
  conversationId: z.string().optional(),
});

export type KnowledgeBaseQueryInput = z.infer<typeof KnowledgeBaseQuerySchema>;
