/* |-------------------------------------------------------------------------- | Agência PSI — Edge Function: sync-email-templates |-------------------------------------------------------------------------- | Sincroniza templates globais ativos para email_templates_tenant. | | POST body: { tenant_id: string, owner_id: string } | | Para cada template em email_templates_global (is_active = true): | - Se não existe no tenant → INSERT com subject/body NULL (herda global) | - Se existe mas synced_version < global.version → UPDATE synced_version | | Retorna: { synced: number, updated: number } |-------------------------------------------------------------------------- */ import { createClient } from 'https://esm.sh/@supabase/supabase-js@2' const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type', 'Access-Control-Allow-Methods': 'POST, OPTIONS', } Deno.serve(async (req: Request) => { // CORS preflight if (req.method === 'OPTIONS') { return new Response('ok', { headers: corsHeaders }) } if (req.method !== 'POST') { return new Response( JSON.stringify({ error: 'Método não permitido' }), { status: 405, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ) } try { const { tenant_id, owner_id } = await req.json() if (!tenant_id || !owner_id) { return new Response( JSON.stringify({ error: 'tenant_id e owner_id são obrigatórios' }), { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ) } const supabase = createClient( Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')! ) // 1. Busca todos os templates globais ativos const { data: globals, error: globalsErr } = await supabase .from('email_templates_global') .select('key, version') .eq('is_active', true) if (globalsErr) throw globalsErr if (!globals || globals.length === 0) { return new Response( JSON.stringify({ synced: 0, updated: 0, message: 'Nenhum template global ativo' }), { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ) } // 2. Busca templates existentes do tenant const { data: tenantTemplates, error: tenantErr } = await supabase .from('email_templates_tenant') .select('template_key, synced_version') .eq('tenant_id', tenant_id) .eq('owner_id', owner_id) if (tenantErr) throw tenantErr const tenantMap = new Map( (tenantTemplates || []).map(t => [t.template_key, t.synced_version]) ) let synced = 0 let updated = 0 for (const global of globals) { const existingVersion = tenantMap.get(global.key) if (existingVersion === undefined) { // Não existe → INSERT com campos null (herda do global) const { error: insertErr } = await supabase .from('email_templates_tenant') .insert({ tenant_id, owner_id, template_key: global.key, subject: null, body_html: null, body_text: null, enabled: true, synced_version: global.version, }) if (insertErr) { console.error(`[sync] Erro ao inserir ${global.key}:`, insertErr.message) continue } synced++ } else if (existingVersion < global.version) { // Existe mas desatualizado → UPDATE apenas synced_version const { error: updateErr } = await supabase .from('email_templates_tenant') .update({ synced_version: global.version }) .eq('tenant_id', tenant_id) .eq('owner_id', owner_id) .eq('template_key', global.key) if (updateErr) { console.error(`[sync] Erro ao atualizar ${global.key}:`, updateErr.message) continue } updated++ } // Se synced_version >= global.version → já está em dia, skip } return new Response( JSON.stringify({ synced, updated }), { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ) } catch (err) { console.error('[sync-email-templates] Erro:', err) return new Response( JSON.stringify({ error: err.message || 'Erro interno' }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ) } })