/*
|--------------------------------------------------------------------------
| Agência PSI — Edge: send-session-status-notification (8.3)
|--------------------------------------------------------------------------
| Disparada por trigger DB quando status de um agenda_evento muda.
| Envia WhatsApp pro paciente usando template apropriado do novo status.
|
| Body JSON:
|   { event_id: "<uuid>", old_status: "agendado", new_status: "cancelado" }
|
| Mapa de template_key por new_status (configurável em notification_templates):
|   - cancelado       → cancelamento_sessao
|   - remarcado       → remarcacao_sessao
|   - confirmado      → confirmacao_sessao
|   - realizado       → pós-sessao (opcional; normalmente desligado)
|   - em_agendamento  → não envia (status intermediário)
|
| Respeita config conversation_bots.respect_optout e registros de opt-out.
| Se template não existe/está desativado pra aquele status, skipa sem erro.
|--------------------------------------------------------------------------
*/

import { 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' }
    })
}

function rewriteForContainer(apiUrl: string): string {
    try {
        const u = new URL(apiUrl)
        if (u.hostname === 'localhost' || u.hostname === '127.0.0.1') {
            u.hostname = 'host.docker.internal'
            return u.toString().replace(/\/+$/, '')
        }
        return apiUrl.replace(/\/+$/, '')
    } catch { return apiUrl }
}

function normalizePhoneBR(raw: string | null | undefined): string {
    const digits = String(raw || '').replace(/\D/g, '')
    if (digits.length === 10 || digits.length === 11) return '55' + digits
    return digits
}

function fmtDate(iso: string): string {
    try { return new Intl.DateTimeFormat('pt-BR', { timeZone: 'America/Sao_Paulo', day: '2-digit', month: 'long' }).format(new Date(iso)) } catch { return iso }
}
function fmtTime(iso: string): string {
    try { return new Intl.DateTimeFormat('pt-BR', { timeZone: 'America/Sao_Paulo', hour: '2-digit', minute: '2-digit', hour12: false }).format(new Date(iso)) } catch { return '' }
}
function renderTemplate(tpl: string, vars: Record<string, string>): string {
    return Object.entries(vars).reduce((acc, [k, v]) => acc.replaceAll(`{{${k}}}`, v ?? ''), tpl)
}

// Mapa de status → template key. Se der pra alguém customizar depois, basta
// criar template com esse key no banco; senão skip silencioso.
const STATUS_TEMPLATE_MAP: Record<string, string> = {
    cancelado: 'cancelamento_sessao',
    remarcado: 'remarcacao_sessao',
    confirmado: 'confirmacao_sessao'
    // realizado/em_agendamento não enviam por padrão
}

async function sendViaEvolution(apiUrl: string, apiKey: string, instance: string, phone: string, text: string) {
    try {
        const endpoint = `${rewriteForContainer(apiUrl)}/message/sendText/${encodeURIComponent(instance)}`
        const resp = await fetch(endpoint, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', apikey: apiKey },
            body: JSON.stringify({ number: phone, text })
        })
        if (!resp.ok) {
            const t = await resp.text()
            return { ok: false, error: `HTTP ${resp.status}: ${t.slice(0, 200)}` }
        }
        const j = await resp.json().catch(() => ({} as Record<string, unknown>))
        const msgId = (j as { key?: { id?: string } }).key?.id || null
        return { ok: true, messageId: msgId }
    } catch (err) {
        return { ok: false, error: (err as Error).message || 'fetch_failed' }
    }
}

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 payload = await req.json().catch(() => null) as { event_id?: string; tenant_id?: string; old_status?: string; new_status?: string } | null
        const eventId = payload?.event_id
        const newStatus = String(payload?.new_status || '').toLowerCase()
        if (!eventId || !newStatus) return json({ ok: false, error: 'invalid_payload' }, 400)

        const templateKey = STATUS_TEMPLATE_MAP[newStatus]
        if (!templateKey) return json({ ok: true, skipped: 'status_not_mapped', status: newStatus })

        const admin = adminClient()

        // Resolve o schema do tenant dono do evento. Preferencialmente o trigger
        // passa tenant_id no body; senão varremos os schemas até achar o evento.
        const evSelect = 'id, inicio_em, modalidade, patient_id, status, patients:patient_id(id, nome_completo, telefone)'

        let tdb: SupabaseClient | null = null
        let tenantId: string | null = payload?.tenant_id ?? null
        let ev: Record<string, unknown> | null = null

        if (tenantId) {
            tdb = await tenantDbForId(admin, tenantId)
            const { data, error: evErr } = await tdb
                .from('agenda_eventos')
                .select(evSelect)
                .eq('id', eventId)
                .maybeSingle()
            if (evErr || !data) return json({ ok: false, error: 'event_not_found' }, 404)
            ev = data as Record<string, unknown>
        } else {
            // Fallback: descobre o tenant procurando o evento em cada schema.
            for (const t of await listTenantSchemas(admin)) {
                const cand = admin.schema(t.schema)
                const { data } = await cand
                    .from('agenda_eventos')
                    .select(evSelect)
                    .eq('id', eventId)
                    .maybeSingle()
                if (data) {
                    tdb = cand
                    tenantId = t.tenantId
                    ev = data as Record<string, unknown>
                    break
                }
            }
            if (!tdb || !ev || !tenantId) return json({ ok: false, error: 'event_not_found' }, 404)
        }

        const evRow = ev as {
            inicio_em: string
            modalidade: string
            patients: { id: string; nome_completo: string | null; telefone: string | null } | Array<{ id: string; nome_completo: string | null; telefone: string | null }>
        }
        const pat = Array.isArray(evRow.patients) ? evRow.patients[0] : evRow.patients
        if (!pat?.telefone) return json({ ok: true, skipped: 'no_phone' })
        const phone = normalizePhoneBR(pat.telefone)
        if (!/^\d{10,15}$/.test(phone)) return json({ ok: true, skipped: 'invalid_phone' })

        // Opt-out: respeita (conversation_optouts é tenant → tdb)
        const { data: optout } = await tdb
            .from('conversation_optouts')
            .select('id')
            .eq('contact_number', phone)
            .is('opted_in_at', null)
            .maybeSingle()
        if (optout) return json({ ok: true, skipped: 'opt_out' })

        // Canal WhatsApp ativo (tenant → tdb)
        const { data: channel } = await tdb
            .from('notification_channels')
            .select('id, provider, credentials')
            .eq('channel', 'whatsapp')
            .eq('is_active', true)
            .is('deleted_at', null)
            .maybeSingle()
        if (!channel) return json({ ok: true, skipped: 'no_active_channel' })

        // Template (notification_templates é tenant → tdb; defaults já semeados no schema)
        const { data: tpl } = await tdb
            .from('notification_templates')
            .select('body_text')
            .eq('channel', 'whatsapp')
            .eq('key', templateKey)
            .is('deleted_at', null)
            .eq('is_active', true)
            .limit(1)
            .maybeSingle()

        const body_text = tpl?.body_text
        if (!body_text) return json({ ok: true, skipped: 'template_not_found', template_key: templateKey })

        // Nome da clínica (tenants é GLOBAL → admin)
        const { data: tenant } = await admin.from('tenants').select('name').eq('id', tenantId).maybeSingle()

        const text = renderTemplate(body_text, {
            nome_paciente: pat.nome_completo || 'paciente',
            data_sessao: fmtDate(evRow.inicio_em),
            hora_sessao: fmtTime(evRow.inicio_em),
            modalidade: evRow.modalidade === 'online' ? 'online' : 'presencial',
            nome_clinica: tenant?.name || '',
            status: newStatus
        })

        const providerKind = channel.provider === 'evolution_api' ? 'evolution' : channel.provider
        if (providerKind !== 'evolution') {
            // Twilio fica pra depois (precisa de créditos + ack)
            return json({ ok: true, skipped: 'provider_not_supported_yet', provider: channel.provider })
        }

        const creds = (channel.credentials ?? {}) as Record<string, string>
        if (!creds.api_url || !creds.api_key || !creds.instance_name) {
            return json({ ok: true, skipped: 'creds_missing' })
        }

        const sendRes = await sendViaEvolution(creds.api_url, creds.api_key, creds.instance_name, phone, text)
        if (!sendRes.ok) return json({ ok: false, error: `send_failed: ${sendRes.error}` }, 500)

        // Registra conversa (conversation_messages é tenant → tdb, sem tenant_id)
        await tdb.from('conversation_messages').insert({
            patient_id: pat.id,
            channel: 'whatsapp',
            direction: 'outbound',
            from_number: null,
            to_number: phone,
            body: text,
            provider: 'evolution',
            provider_message_id: sendRes.messageId ?? null,
            provider_raw: { status_change: true, event_id: eventId, old_status: payload?.old_status || null, new_status: newStatus },
            kanban_status: 'awaiting_patient',
            responded_at: new Date().toISOString()
        })

        return json({ ok: true, sent: true, template_key: templateKey, to: phone })
    } catch (err) {
        console.error('[send-session-status-notification] fatal:', err)
        return json({ ok: false, error: (err as Error).message || 'unexpected' }, 500)
    }
})
