/*
|--------------------------------------------------------------------------
| Agência PSI — Edge: send-session-reminder-manual (8.2)
|--------------------------------------------------------------------------
| Dispara lembrete on-demand pra um evento específico, a partir do botão
| "Lembrar paciente" na agenda. Reusa template lembrete_sessao.
|
| Body: { event_id: "<uuid>" }
|
| Diferente do cron send-session-reminders:
|   - Sem janela temporal (aceita evento em qualquer horário futuro)
|   - Sem dedup (terapeuta pode disparar quantas vezes quiser — log entra
|     como reminder_type='manual')
|   - Permite disparar evento mesmo com status não 'agendado' (útil pra
|     confirmar cancelamentos etc)
|--------------------------------------------------------------------------
*/

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

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 fmtDateDayMonth(iso: string): string {
    try {
        const d = new Date(iso)
        return new Intl.DateTimeFormat('pt-BR', { timeZone: 'America/Sao_Paulo', day: '2-digit', month: 'long' }).format(d)
    } catch { return iso }
}

function fmtTime(iso: string): string {
    try {
        const d = new Date(iso)
        return new Intl.DateTimeFormat('pt-BR', { timeZone: 'America/Sao_Paulo', hour: '2-digit', minute: '2-digit', hour12: false }).format(d)
    } catch { return '' }
}

function renderTemplate(tpl: string, vars: Record<string, string>): string {
    return Object.entries(vars).reduce(
        (acc, [k, v]) => acc.replaceAll(`{{${k}}}`, v ?? ''),
        tpl
    )
}

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 body = await req.json().catch(() => null) as { event_id?: string, tenant_id?: string } | null
        const eventId = body?.event_id
        const tenantId = body?.tenant_id
        if (!eventId) return json({ ok: false, error: 'event_id_required' }, 400)
        // tenant_id é obrigatório no schema-per-tenant: o evento vive no schema do
        // tenant, então precisamos dele pra resolver o schema antes de qualquer query.
        if (!tenantId) return json({ ok: false, error: 'tenant_id_required' }, 400)

        // Auth: precisa de user (qualquer membro do tenant do evento)
        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

        const supa = adminClient()

        // Client ligado ao schema do tenant (agenda_eventos, patients,
        // notification_channels/templates, conversation_messages, session_reminder_logs).
        let tdb
        try {
            tdb = await tenantDbForId(supa, tenantId)
        } catch (e) {
            console.error('[send-session-reminder-manual] schema indisponível:', (e as Error).message)
            return json({ ok: false, error: 'tenant_invalido' }, 400)
        }

        // Carrega evento + paciente (tabela tenant)
        const { data: ev, error: evErr } = await tdb
            .from('agenda_eventos')
            .select('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)

        // Autoriza: user deve ser membro ativo do tenant (global tenant_members)
        const { data: mem } = await supa
            .from('tenant_members')
            .select('id')
            .eq('tenant_id', tenantId)
            .eq('user_id', userId)
            .eq('status', 'active')
            .maybeSingle()
        if (!mem) return json({ ok: false, error: 'forbidden' }, 403)

        const pat = Array.isArray(ev.patients) ? ev.patients[0] : ev.patients
        if (!pat || !pat.telefone) return json({ ok: false, error: 'no_phone' }, 400)

        const phone = normalizePhoneBR(pat.telefone)
        if (!/^\d{10,15}$/.test(phone)) return json({ ok: false, error: 'invalid_phone' }, 400)

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

        // Tenant name (global tenants)
        const { data: tenant } = await supa.from('tenants').select('name').eq('id', tenantId).maybeSingle()

        // Template lembrete_sessao — tenta custom, fallback pro default (tabela tenant)
        const { data: tpl } = await tdb
            .from('notification_templates')
            .select('body_text')
            .eq('channel', 'whatsapp')
            .eq('key', 'lembrete_sessao')
            .is('deleted_at', null)
            .eq('is_active', true)
            .order('is_custom', { ascending: false })
            .limit(1)
            .maybeSingle()

        let body_text = tpl?.body_text
        if (!body_text) {
            // Fallback: template default semeado no schema (is_custom=false)
            const { data: def } = await tdb
                .from('notification_templates')
                .select('body_text')
                .eq('channel', 'whatsapp')
                .eq('key', 'lembrete_sessao')
                .eq('is_custom', false)
                .is('deleted_at', null)
                .eq('is_active', true)
                .limit(1)
                .maybeSingle()
            body_text = def?.body_text
        }
        if (!body_text) return json({ ok: false, error: 'template_not_found' }, 400)

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

        const providerKind = channel.provider === 'evolution_api' ? 'evolution' : channel.provider

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

            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 + log (tabelas tenant)
            const { data: msg } = 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: { reminder_type: 'manual', event_id: eventId, triggered_by: userId },
                kanban_status: 'awaiting_patient',
                responded_at: new Date().toISOString()
            }).select('id').single()

            // Upsert: permitir re-disparo manual. UNIQUE (event_id, reminder_type) — sobrescreve anterior.
            await tdb.from('session_reminder_logs').upsert({
                event_id: eventId,
                reminder_type: 'manual',
                provider: 'evolution',
                to_phone: phone,
                provider_message_id: sendRes.messageId ?? null,
                conversation_message_id: msg?.id ?? null,
                sent_at: new Date().toISOString()
            }, { onConflict: 'event_id,reminder_type' })

            return json({ ok: true, sent: true, provider: 'evolution', to: phone, body_preview: text.slice(0, 100) })
        }

        // Twilio: implementação futura (escopo desta iteração é Evolution)
        return json({ ok: false, error: `provider_not_supported_manual: ${channel.provider}` }, 400)
    } catch (err) {
        console.error('[send-session-reminder-manual] fatal:', err)
        return json({ ok: false, error: (err as Error).message || 'unexpected' }, 500)
    }
})
