import type { Operation } from './usePrintQueue' export interface PrintTemplate { id: string name: string description?: string operations: Operation[] createdAt: string updatedAt: string } export function useTemplates() { const templates = useState('templates', () => []) const loading = useState('templatesLoading', () => false) const error = useState('templatesError', () => null) // Cargar templates del servidor async function fetchTemplates(): Promise { loading.value = true error.value = null try { const data = await $fetch('/api/templates') templates.value = data } catch (e) { console.error('Error fetching templates:', e) error.value = 'Error al cargar templates' } finally { loading.value = false } } // Guardar nuevo template async function saveTemplate( name: string, description: string, operations: Operation[] ): Promise { error.value = null try { const template = await $fetch('/api/templates', { method: 'POST', body: { name, description, operations } }) templates.value = [...templates.value, template] return template } catch (e) { console.error('Error saving template:', e) error.value = 'Error al guardar template' return null } } // Actualizar template existente async function updateTemplate( id: string, updates: Partial<{ name: string; description: string; operations: Operation[] }> ): Promise { error.value = null try { const template = await $fetch(`/api/templates/${id}`, { method: 'PUT', body: updates }) templates.value = templates.value.map(t => t.id === id ? template : t) return template } catch (e) { console.error('Error updating template:', e) error.value = 'Error al actualizar template' return null } } // Eliminar template async function deleteTemplate(id: string): Promise { error.value = null try { await $fetch(`/api/templates/${id}`, { method: 'DELETE' }) templates.value = templates.value.filter(t => t.id !== id) return true } catch (e) { console.error('Error deleting template:', e) error.value = 'Error al eliminar template' return false } } // Cargar operaciones de un template function loadTemplate(id: string): Operation[] | null { const template = templates.value.find(t => t.id === id) return template ? JSON.parse(JSON.stringify(template.operations)) : null } // Duplicar template async function duplicateTemplate(id: string): Promise { error.value = null try { const template = await $fetch(`/api/templates/${id}/duplicate`, { method: 'POST' }) templates.value = [...templates.value, template] return template } catch (e) { console.error('Error duplicating template:', e) error.value = 'Error al duplicar template' return null } } return { templates: readonly(templates), loading: readonly(loading), error: readonly(error), fetchTemplates, saveTemplate, updateTemplate, deleteTemplate, loadTemplate, duplicateTemplate } }