import React, { useState, useEffect } from 'react'; import type { Backup, BackupData } from '../app'; import { backupAPI } from '../../api/backup-api'; import { CustomerConfigService } from '../../stores/customer-config'; import { ConfirmDialog } from './ConfirmDialog'; export type TransferDirection = 'restore' | 'promote' | 'export'; export type TransferTarget = 'environment' | 'test-data' | 'file-system'; interface DataTransferProps { direction: TransferDirection; target: TransferTarget; onBack: () => void; // For single backup operations (restore) backup?: Backup | null; backupData?: BackupData | null; // For multi-backup operations (promotion/export) backups?: Backup[]; selectedBackupIds?: string[]; } interface TransferSelection { personas: string[]; conversations: string[]; replicas: string[]; objectives: string[]; guardrails: string[]; } interface PersonaInfo { global_persona_id: string; name: string; customer_id: string; environment: string; backup_id: string; } interface TransferOptions { targetEnvironment?: string; targetLocation?: string; includeUnassigned?: boolean; customerNameOverrides?: Record; preserveCustomerRelationships?: boolean; } export function DataTransfer({ direction, target, onBack, backup, backupData: _backupData, backups = [], selectedBackupIds = [] }: DataTransferProps) { const [_selectedItems, _setSelectedItems] = useState({ personas: [], conversations: [], replicas: [], objectives: [], guardrails: [] }); const [transferOptions, setTransferOptions] = useState({ targetEnvironment: '', targetLocation: '../fake-tavus-server/backup-data/customers', includeUnassigned: true, customerNameOverrides: {}, preserveCustomerRelationships: true // Always preserve customer relationships }); const [selectedBackups, _setSelectedBackups] = useState(selectedBackupIds); const [selectedPersonas, setSelectedPersonas] = useState([]); const [availablePersonas, setAvailablePersonas] = useState([]); const [isTransferring, setIsTransferring] = useState(false); const [transferResult, setTransferResult] = useState(null); const [preview, setPreview] = useState(null); const [validation, setValidation] = useState(null); const [_loading, setLoading] = useState(false); const [error, setError] = useState(null); const [confirmDialog, setConfirmDialog] = useState<{ isOpen: boolean; title: string; description: string; onConfirm: () => void; onClose: () => void; isDestructive?: boolean; }>({ isOpen: false, title: '', description: '', onConfirm: () => { /* no-op */ }, onClose: () => setConfirmDialog(prev => ({ ...prev, isOpen: false })), isDestructive: false }); // Determine what we're working with const isMultiBackup = direction !== 'restore'; const workingBackups = isMultiBackup ? backups.filter(b => selectedBackups.includes(b.backup_id)) : backup ? [backup] : []; useEffect(() => { if (isMultiBackup) { void loadPersonasFromBackups(); } }, [backups]); useEffect(() => { if (selectedBackups.length > 0 && isMultiBackup) { void loadPreview(); } }, [selectedBackups, transferOptions]); useEffect(() => { if (target === 'test-data' && transferOptions.targetLocation) { void validateTarget(); } }, [transferOptions.targetLocation]); const loadPersonasFromBackups = async () => { try { const personas: PersonaInfo[] = []; for (const backup of backups) { try { const backupData = await backupAPI.getBackupData(backup.backup_id); if (backupData?.personas && Array.isArray(backupData.personas)) { for (const persona of backupData.personas) { personas.push({ global_persona_id: persona.persona_id || persona.global_persona_id, name: persona.persona_name || persona.name, customer_id: backup.customer_id, environment: backup.metadata?.environment || 'unknown', backup_id: backup.backup_id }); } } } catch (_err) { console.warn(`Failed to load personas from backup ${backup.backup_id}:`, err); } } setAvailablePersonas(personas); } catch (_err) { console.error('Failed to load personas from backups:', err); } }; const loadPreview = async () => { if (selectedBackups.length === 0 && isMultiBackup) return; try { setLoading(true); setError(null); if (direction === 'export' && target === 'test-data') { const result = await backupAPI.getPromotionPreview(selectedBackups); setPreview(result); } else { // For restore/environment promotion, create a simple preview const totalPersonas = workingBackups.reduce((sum, b) => sum + (b.metadata?.personas_count || 0), 0); const totalConversations = workingBackups.reduce((sum, b) => sum + (b.metadata?.conversations_count || 0), 0); setPreview({ totalBackups: workingBackups.length, totalCustomers: new Set(workingBackups.map(b => b.customer_id)).size, dataBreakdown: { personas: totalPersonas, conversations: totalConversations, replicas: workingBackups.reduce((sum, b) => sum + (b.metadata?.replicas_count || 0), 0), objectives: workingBackups.reduce((sum, b) => sum + (b.metadata?.objectives_count || 0), 0), guardrails: workingBackups.reduce((sum, b) => sum + (b.metadata?.guardrails_count || 0), 0) } }); } } catch (_err) { setError(_err instanceof Error ? _err.message : 'Failed to load preview'); } finally { setLoading(false); } }; const validateTarget = async () => { try { if (target === 'test-data') { const result = await backupAPI.validatePromotionTarget(transferOptions.targetLocation!); setValidation(result); } } catch (_err) { setValidation({ exists: false, writable: false, message: 'Failed to validate target' }); } }; const handlePersonaSelection = (personaId: string) => { setSelectedPersonas(prev => { if (prev.includes(personaId)) { return prev.filter(id => id !== personaId); } else { return [...prev, personaId]; } }); }; const handleSelectAllPersonas = () => { if (selectedPersonas.length === availablePersonas.length) { setSelectedPersonas([]); } else { setSelectedPersonas(availablePersonas.map(p => p.global_persona_id)); } }; const handleTransfer = async () => { const selectedBackupIds = isMultiBackup ? selectedBackups : backup ? [backup.backup_id] : []; if (selectedBackupIds.length === 0) { setError('Please select at least one backup'); return; } try { setIsTransferring(true); setError(null); let result; if (direction === 'export' && target === 'test-data') { // Data promotion to test environment result = await backupAPI.promoteToTestData({ backupIds: selectedBackupIds, targetLocation: transferOptions.targetLocation, includeUnassigned: transferOptions.includeUnassigned, customerNameOverrides: transferOptions.customerNameOverrides }); } else if (direction === 'restore' || direction === 'promote') { // Environment restore/promotion result = await backupAPI.promoteToEnvironment( selectedBackupIds[0], transferOptions.targetEnvironment!, { customerId: backup?.customer_id, customerName: backup?.customer_name, sourceEnvironment: backup?.metadata?.environment, preserveCustomerRelationships: transferOptions.preserveCustomerRelationships } ); } else { throw new Error(`Unsupported operation: ${direction} to ${target}`); } setTransferResult(result); } catch (_err) { setError(_err instanceof Error ? _err.message : 'Transfer failed'); } finally { setIsTransferring(false); } }; const getTitle = () => { if (direction === 'restore') return 'Restore Data'; if (direction === 'promote') return 'Promote Data'; if (direction === 'export' && target === 'test-data') return 'Export to Test Data'; return 'Transfer Data'; }; const getActionButtonText = () => { if (isTransferring) { return direction === 'restore' ? 'Restoring...' : direction === 'promote' ? 'Promoting...' : 'Exporting...'; } return direction === 'restore' ? 'Restore Selected Data' : direction === 'promote' ? 'Promote Selected Data' : 'Export Selected Data'; }; const getTargetOptions = () => { if (direction === 'restore' || direction === 'promote') { return ['testing', 'staging', 'production'].map(env => ( )); } return null; }; return (
{/* Header */}

{getTitle()}

{/* Error Display */} {error && (
{error}
)} {/* Success Result */} {transferResult && (
✓

Transfer Successful

{transferResult.message}

{transferResult._targetPath && (

Target: {transferResult._targetPath}

)}
)} {/* Target Configuration */}

Target Configuration

{/* Environment Selection for restore/promote */} {(direction === 'restore' || direction === 'promote') && (
)} {/* Location input for test data export */} {target === 'test-data' && (
setTransferOptions(prev => ({...prev, targetLocation: e.target.value}))} className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 font-mono text-sm" /> {/* Validation Status */} {validation && (
{validation.exists && validation.writable ? '✓' : '⚠️'} Target Validation

{validation.message}

)}
)} {/* Options */}
setTransferOptions(prev => ({...prev, includeUnassigned: e.target.checked}))} className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded" />
{/* Note: Customer relationships are always preserved - no longer a user option */}
{/* Persona Selection (for promotion operations) */} {isMultiBackup && (

Select Personas ({selectedPersonas.length} selected)

{availablePersonas.map((persona) => (
handlePersonaSelection(persona.global_persona_id)} className="mt-1 h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded" />

{persona.name}

{persona.environment}

Customer: {CustomerConfigService.getDisplayName(persona.customer_id)}

ID: {persona.global_persona_id}

))} {availablePersonas.length === 0 && (

No personas found in selected backups.

Please select backups that contain persona data.

)}
)} {/* Preview */} {preview && (

Transfer Preview

Summary

Total Backups: {preview.totalBackups}

Total Customers: {preview.totalCustomers}

Data Breakdown

Personas: {preview.dataBreakdown.personas}

Conversations: {preview.dataBreakdown.conversations}

Replicas: {preview.dataBreakdown.replicas}

Objectives: {preview.dataBreakdown.objectives}

Guardrails: {preview.dataBreakdown.guardrails}

)} {/* Action Buttons */}
); }