/*
|--------------------------------------------------------------------------
| Agência PSI — Edge Function: reactivate-notification-channel
|--------------------------------------------------------------------------
| Reativa um canal de notificação previamente soft-deleted (deleted_at IS NOT NULL
| ou is_active=false). Usa service_role pra bypass RLS.
|
| Casos de uso:
|   - SaaS admin reconfigura WhatsApp pra tenant que já tinha canal antigo
|   - Tenant volta de Twilio pra Evolution (ou vice-versa) pelo chooser
|
| Inputs aceitos (um OU o outro):
|   { channel_id: "<uuid>" }                              — reativa canal específico
|   { tenant_id: "<uuid>", provider: "evolution_api" }    — reativa por tenant+provider
|   { tenant_id: "<uuid>", provider: "twilio" }
|
| Exclusividade: soft-deleta qualquer OUTRO canal ativo do mesmo tenant+channel
| (ex: se estava ativo Twilio e reativa Evolution, Twilio é soft-deletado).
|
| Autoriza: saas_admin OU membro ativo do tenant dono do canal.
| Limpa `metadata.first_unhealthy_at` e `connection_status='disconnected'` ao
| reativar (garante heartbeat começa de estado limpo).
|--------------------------------------------------------------------------
*/

import { createClient, type SupabaseClient } from 'https://esm.sh/@supabase/supabase-js@2'
import { adminClient, tenantDbForId, listTenantSchemas } 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',
}

function json(body: unknown, status = 200) {
    return new Response(JSON.stringify(body), {
        status,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    })
}

Deno.serve(async (req: Request) => {
    if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })
    if (req.method !== 'POST') return json({ ok: false, error: 'method_not_allowed' }, 405)

    try {
        const body = await req.json().catch(() => null) as {
            channel_id?: string
            tenant_id?: string
            provider?: string
        } | null

        const channelId = body?.channel_id
        const tenantId = body?.tenant_id
        const provider = body?.provider

        if (!channelId && (!tenantId || !provider)) {
            return json({ ok: false, error: 'invalid_input: precisa de channel_id OU (tenant_id + provider)' }, 400)
        }

        // Auth: valida user via JWT
        const authHeader = req.headers.get('Authorization')
        if (!authHeader) return json({ ok: false, error: 'unauthorized' }, 401)

        const supaAuth = createClient(
            Deno.env.get('SUPABASE_URL')!,
            Deno.env.get('SUPABASE_ANON_KEY')!,
            { global: { headers: { Authorization: authHeader } } }
        )
        const { data: authData, error: authErr } = await supaAuth.auth.getUser()
        if (authErr || !authData?.user) return json({ ok: false, error: 'unauthorized' }, 401)
        const userId = authData.user.id

        // Service role pra bypass RLS
        const supaSvc = adminClient()

        // schema-per-tenant: notification_channels vive no schema do tenant (sem
        // coluna tenant_id). Resolvemos o schema (tdb) + o tenant dono (targetTenantId).
        let tdb: SupabaseClient | null = null
        let targetTenantId: string | null = null
        let target: { id: string, channel: string, provider: string, metadata: Record<string, unknown> | null } | null = null

        if (channelId) {
            // Só temos channel_id — varremos os schemas provisionados pra achar o canal.
            // NÃO filtramos por deleted_at: o alvo geralmente está soft-deleted.
            for (const ref of await listTenantSchemas(supaSvc)) {
                const candidate = supaSvc.schema(ref.schema)
                const { data, error } = await candidate
                    .from('notification_channels')
                    .select('id, channel, provider, metadata')
                    .eq('id', channelId)
                    .maybeSingle()
                if (error) {
                    console.warn('[reactivate] busca canal em', ref.schema, ':', error.message)
                    continue
                }
                if (data) { tdb = candidate; targetTenantId = ref.tenantId; target = data; break }
            }
        } else {
            // tenant_id + provider: schema conhecido. Busca o mais recente daquele provider.
            try {
                tdb = await tenantDbForId(supaSvc, tenantId!)
            } catch (e) {
                console.error('[reactivate] schema indisponível:', (e as Error).message)
                return json({ ok: false, error: 'tenant_invalido' }, 400)
            }
            targetTenantId = tenantId!
            const { data } = await tdb
                .from('notification_channels')
                .select('id, channel, provider, metadata')
                .eq('provider', provider!)
                .eq('channel', 'whatsapp')
                .order('created_at', { ascending: false })
                .limit(1)
                .maybeSingle()
            target = data
        }

        if (!tdb || !targetTenantId || !target) return json({ ok: false, error: 'channel_not_found' }, 404)

        // Autoriza: saas_admin OU membro ativo do tenant
        const { data: isAdmin } = await supaSvc.rpc('is_saas_admin')
        let authorized = !!isAdmin
        if (!authorized) {
            const { data: membership } = await supaSvc
                .from('tenant_members')
                .select('id')
                .eq('tenant_id', targetTenantId)
                .eq('user_id', userId)
                .eq('status', 'active')
                .maybeSingle()
            authorized = !!membership
        }
        if (!authorized) return json({ ok: false, error: 'forbidden' }, 403)

        // Exclusividade: soft-deleta outros canais ativos do mesmo channel (tabela
        // tenant — o escopo do tenant já é o próprio schema, sem tenant_id)
        const nowIso = new Date().toISOString()
        const { data: others } = await tdb
            .from('notification_channels')
            .select('id')
            .eq('channel', target.channel)
            .neq('id', target.id)
            .is('deleted_at', null)

        let deactivatedOthers = 0
        if (others && others.length > 0) {
            const { error: deactErr } = await tdb
                .from('notification_channels')
                .update({ is_active: false, deleted_at: nowIso })
                .in('id', others.map((o) => o.id))
            if (deactErr) {
                console.error('[reactivate] failed to deactivate others:', deactErr.message)
                return json({ ok: false, error: 'failed_to_ensure_exclusivity', detail: deactErr.message }, 500)
            }
            deactivatedOthers = others.length
        }

        // Reativa o alvo: limpa deleted_at, ativa, reseta connection_status e
        // first_unhealthy_at do metadata (heartbeat começa zerado).
        const cleanedMeta: Record<string, unknown> = { ...(target.metadata || {}) }
        delete cleanedMeta.first_unhealthy_at

        const { error: updErr } = await tdb
            .from('notification_channels')
            .update({
                is_active: true,
                deleted_at: null,
                connection_status: 'disconnected',
                last_health_check: null,
                metadata: cleanedMeta
            })
            .eq('id', target.id)

        if (updErr) {
            console.error('[reactivate] update error:', updErr.message)
            return json({ ok: false, error: updErr.message }, 500)
        }

        return json({
            ok: true,
            channel_id: target.id,
            provider: target.provider,
            tenant_id: targetTenantId,
            deactivated_others: deactivatedOthers
        })
    } catch (err) {
        console.error('[reactivate-notification-channel] fatal:', err)
        return json({ ok: false, error: String(err) }, 500)
    }
})
