/*
|--------------------------------------------------------------------------
| 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 { adminClient, tenantDbForId } from '../_shared/tenant.ts'

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 admin = adminClient()
    // email_templates_tenant é TENANT → tdb (schema do tenant)
    const tdb = await tenantDbForId(admin, tenant_id)

    // 1. Busca todos os templates globais ativos (GLOBAL → admin)
    const { data: globals, error: globalsErr } = await admin
      .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 (TENANT → tdb, sem tenant_id)
    const { data: tenantTemplates, error: tenantErr } = await tdb
      .from('email_templates_tenant')
      .select('template_key, synced_version')
      .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). Tenant → tdb, sem tenant_id.
        const { error: insertErr } = await tdb
          .from('email_templates_tenant')
          .insert({
            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 (tenant → tdb)
        const { error: updateErr } = await tdb
          .from('email_templates_tenant')
          .update({ synced_version: global.version })
          .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' } }
    )
  }
})
