import React, { useState, useEffect } from 'react'; import type { Backup } from '../app'; import { backupAPI } from '../../api/backup-api'; import { CustomerConfigService } from '../../stores/customer-config'; import { ConfirmDialog } from './ConfirmDialog'; interface PersonaPromotionProps { backups: Backup[]; onBack: () => void; } interface PersonaInfo { global_persona_id: string; name: string; customer_id: string; customer_name: string; environment: string; backup_id: string; created_at: string; } export function PersonaPromotion({ backups, onBack }: PersonaPromotionProps) { const [personas, setPersonas] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [processing, setProcessing] = useState(null); const [filter, setFilter] = useState({ customer: '', environment: '', search: '' }); const [confirmDialog, setConfirmDialog] = useState<{ isOpen: boolean; title: string; description: string; onConfirm: () => void; onClose: () => void; isDestructive?: boolean; details?: { action: 'create' | 'replace'; conflictingPersona?: PersonaInfo; }; }>({ isOpen: false, title: '', description: '', // Default placeholder - will be replaced when dialog is actually used // eslint-disable-next-line @typescript-eslint/no-empty-function onConfirm: () => {}, onClose: () => setConfirmDialog(prev => ({ ...prev, isOpen: false })), isDestructive: false }); useEffect(() => { void loadPersonas(); }, [backups]); // Helper function to find persona name conflicts in target environment const findNameConflict = (personaName: string, targetEnvironment: string, excludePersonaId?: string): PersonaInfo | undefined => { return personas.find(p => p.name === personaName && p.environment === targetEnvironment && p.global_persona_id !== excludePersonaId ); }; // Helper function to determine promotion action type const getPromotionDetails = (persona: PersonaInfo, targetEnvironment: string) => { const conflict = findNameConflict(persona.name, targetEnvironment, persona.global_persona_id); return { action: conflict ? 'replace' as const : 'create' as const, conflictingPersona: conflict, willReplace: !!conflict }; }; const loadPersonas = async () => { try { setLoading(true); setError(null); // Get the list of excluded stock personas const excludedStockPersonas = backupAPI.getExcludedStockPersonas(); const personaList: 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) { // Filter out excluded stock personas if (!excludedStockPersonas.includes(persona.name)) { personaList.push({ global_persona_id: persona.global_persona_id, name: persona.name, customer_id: backup.customer_id, customer_name: backup.customer_name, environment: backup.metadata?.environment || 'unknown', backup_id: backup.backup_id, created_at: backup.created_at }); } } } } catch (_err) { console.warn(`Failed to load personas from backup ${backup.backup_id}:`, err); } } setPersonas(personaList); } catch (_err) { setError(_err instanceof Error ? err.message : 'Failed to load personas'); } finally { setLoading(false); } }; const handlePromote = async (persona: PersonaInfo, targetEnvironment: string) => { const actionText = getPromotionActionText(persona.environment, targetEnvironment); const promotionDetails = getPromotionDetails(persona, targetEnvironment); let description = ''; let title = ''; if (promotionDetails.willReplace) { const conflict = promotionDetails.conflictingPersona; title = `${actionText} and Replace Existing Persona`; description = `⚠️ WARNING: A persona named "${persona.name}" already exists in ${targetEnvironment}. This action will: • ${actionText} "${persona.name}" from ${persona.environment} to ${targetEnvironment} • REPLACE the existing "${conflict.name}" persona (ID: ${conflict.global_persona_id}) • The existing persona in ${targetEnvironment} will be permanently overwritten Customer: ${CustomerConfigService.getDisplayName(persona.customer_id)} Are you sure you want to proceed with this replacement?`; } else { title = `${actionText} Persona`; description = `This action will create a new persona in ${targetEnvironment}: • ${actionText} "${persona.name}" from ${persona.environment} to ${targetEnvironment} • CREATE new persona in ${targetEnvironment} (no conflicts found) • Customer: ${CustomerConfigService.getDisplayName(persona.customer_id)} Are you sure you want to proceed?`; } setConfirmDialog({ isOpen: true, title, description, details: { action: promotionDetails.action, conflictingPersona: promotionDetails.conflictingPersona }, onConfirm: async () => { try { setProcessing(persona.global_persona_id); setError(null); const result = await backupAPI.promoteToEnvironment( persona.backup_id, targetEnvironment, { customerId: persona.customer_id, customerName: persona.customer_name, sourceEnvironment: persona.environment, preserveCustomerRelationships: true, personaIds: [persona.global_persona_id], // Only promote this specific persona promotionDetails: { action: promotionDetails.action, willReplace: promotionDetails.willReplace, conflictingPersona: promotionDetails.conflictingPersona } } ); console.log(`Successfully ${promotionDetails.action === 'replace' ? 'replaced' : 'created'} persona ${persona.name}:`, result); // Refresh the persona list await loadPersonas(); } catch (_err) { setError(_err instanceof Error ? err.message : `Failed to ${actionText.toLowerCase()} persona`); } finally { setProcessing(null); setConfirmDialog(prev => ({ ...prev, isOpen: false })); } }, onClose: () => setConfirmDialog(prev => ({ ...prev, isOpen: false })), isDestructive: promotionDetails.willReplace }); }; const getPromotionActionText = (currentEnv: string, targetEnv: string): string => { const envOrder = ['testing', 'staging', 'production']; const currentIndex = envOrder.indexOf(currentEnv); const targetIndex = envOrder.indexOf(targetEnv); if (targetIndex > currentIndex) return 'Promote'; if (targetIndex < currentIndex) return 'Demote'; return 'Move'; }; const getAvailableTargets = (currentEnvironment: string): string[] => { const allEnvironments = ['testing', 'staging', 'production']; return allEnvironments.filter(env => env !== currentEnvironment); }; const getEnvironmentBadge = (environment: string) => { const colors: Record = { testing: 'bg-blue-100 text-blue-800', staging: 'bg-yellow-100 text-yellow-800', production: 'bg-green-100 text-green-800' }; return colors[environment] || 'bg-gray-100 text-gray-800'; }; const filteredPersonas = personas.filter(persona => { const matchesCustomer = !filter.customer || persona.customer_id === filter.customer; const matchesEnvironment = !filter.environment || persona.environment === filter.environment; const matchesSearch = !filter.search || persona.name.toLowerCase().includes(filter.search.toLowerCase()) || persona.customer_name.toLowerCase().includes(filter.search.toLowerCase()); return matchesCustomer && matchesEnvironment && matchesSearch; }); const uniqueCustomers = Array.from(new Set(personas.map(p => p.customer_id))) .map(id => ({ id, name: personas.find(p => p.customer_id === id)?.customer_name || id })); const uniqueEnvironments = Array.from(new Set(personas.map(p => p.environment))); if (loading) { return (

Persona Promotion

Loading personas...
); } return (
{/* Header */}

Persona Promotion

{/* Filters */}
setFilter(prev => ({ ...prev, search: e.target.value }))} placeholder="Search personas or customers..." className="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 text-sm" />
{/* Error Display */} {error && (
{error}
)} {/* Personas List */}

Personas ({filteredPersonas.length} found)

{filteredPersonas.map((persona) => { const availableTargets = getAvailableTargets(persona.environment); const isProcessing = processing === persona.global_persona_id; return (

{persona.name}

{persona.environment}

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

ID: {persona.global_persona_id}

{availableTargets.map(targetEnv => { const actionText = getPromotionActionText(persona.environment, targetEnv); const isPromoting = actionText === 'Promote'; const promotionDetails = getPromotionDetails(persona, targetEnv); const willReplace = promotionDetails.willReplace; return (
{willReplace && (
Will replace existing "{promotionDetails.conflictingPersona.name}"
)}
); })}
); })} {filteredPersonas.length === 0 && (

No Personas Found

{personas.length === 0 ? 'No personas found in the selected backups.' : 'No personas match the current filters.'}

)}
{confirmDialog.description}
{confirmDialog.details?.action === 'replace' && confirmDialog.details.conflictingPersona && (
Conflicting Persona Details:
• Name: {confirmDialog.details.conflictingPersona.name}
• ID: {confirmDialog.details.conflictingPersona.global_persona_id}
• Customer: {CustomerConfigService.getDisplayName(confirmDialog.details.conflictingPersona.customer_id)}
• Environment: {confirmDialog.details.conflictingPersona.environment}
)} {confirmDialog.details?.action === 'create' && (
✅ Safe Operation
No existing persona with this name found in the target environment.
)}
} /> ); }