/*
|--------------------------------------------------------------------------
| 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 { 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',
}

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; 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 supa = createClient(
            Deno.env.get('SUPABASE_URL')!,
            Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!
        )

        // Carrega evento + paciente
        const { data: ev, error: evErr } = await supa
            .from('agenda_eventos')
            .select('id, tenant_id, inicio_em, modalidade, patient_id, status, patients:patient_id(id, nome_completo, telefone)')
            .eq('id', eventId)
            .maybeSingle()

        if (evErr || !ev) return json({ ok: false, error: 'event_not_found' }, 404)

        const pat = Array.isArray(ev.patients) ? ev.patients[0] : ev.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
        const { data: optout } = await supa
            .from('conversation_optouts')
            .select('id')
            .eq('tenant_id', ev.tenant_id)
            .eq('contact_number', phone)
            .is('opted_in_at', null)
            .maybeSingle()
        if (optout) return json({ ok: true, skipped: 'opt_out' })

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

        // Template (tenant-specific → global default)
        const { data: tpl } = await supa
            .from('notification_templates')
            .select('body_text')
            .eq('tenant_id', ev.tenant_id)
            .eq('channel', 'whatsapp')
            .eq('key', templateKey)
            .is('deleted_at', null)
            .eq('is_active', true)
            .limit(1)
            .maybeSingle()

        let body_text = tpl?.body_text
        if (!body_text) {
            const { data: def } = await supa
                .from('notification_templates')
                .select('body_text')
                .eq('channel', 'whatsapp')
                .eq('key', templateKey)
                .is('tenant_id', null)
                .is('deleted_at', null)
                .eq('is_active', true)
                .limit(1)
                .maybeSingle()
            body_text = def?.body_text
        }
        if (!body_text) return json({ ok: true, skipped: 'template_not_found', template_key: templateKey })

        const { data: tenant } = await supa.from('tenants').select('name').eq('id', ev.tenant_id).maybeSingle()

        const text = renderTemplate(body_text, {
            nome_paciente: pat.nome_completo || 'paciente',
            data_sessao: fmtDate(ev.inicio_em),
            hora_sessao: fmtTime(ev.inicio_em),
            modalidade: ev.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 (sem log unique — transições podem acontecer várias vezes)
        await supa.from('conversation_messages').insert({
            tenant_id: ev.tenant_id,
            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)
    }
})
