/*
|--------------------------------------------------------------------------
| Agência PSI — Edge Function: send-session-reminders
|--------------------------------------------------------------------------
| Dispara lembretes WhatsApp pra sessões futuras. Chamado por pg_cron a cada
| 15 minutos.
|
| Busca eventos com inicio_em dentro das janelas:
|   - 24h ± 15min  (envio do lembrete de 24h)
|   - 2h  ± 15min  (envio do lembrete de 2h)
|
| Checa per-evento:
|   - settings.enabled do tenant
|   - quiet_hours (agora está dentro da janela silenciosa?)
|   - opt-out do paciente
|   - canal ativo (Evolution/Twilio)
|   - log unique: nao duplica
|
| Suporta apenas Evolution no momento (Twilio virá com Marco B - créditos).
|--------------------------------------------------------------------------
*/

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

// Verifica se o momento atual (em São Paulo) está dentro da janela quiet_hours
function isQuietHoursNow(startHHMM: string, endHHMM: string): boolean {
    const now = new Date()
    const fmt = new Intl.DateTimeFormat('en-US', {
        timeZone: 'America/Sao_Paulo',
        hour: '2-digit', minute: '2-digit', hour12: false
    })
    const parts = fmt.formatToParts(now)
    const h = parseInt(parts.find((p) => p.type === 'hour')?.value || '0', 10)
    const m = parseInt(parts.find((p) => p.type === 'minute')?.value || '0', 10)
    const mins = h * 60 + m
    const [sh, sm] = startHHMM.split(':').map(Number)
    const [eh, em] = endHHMM.split(':').map(Number)
    const startMin = (sh || 0) * 60 + (sm || 0)
    const endMin = (eh || 0) * 60 + (em || 0)
    if (startMin === endMin) return false
    if (startMin < endMin) {
        // janela normal (ex: 08:00-12:00)
        return mins >= startMin && mins < endMin
    }
    // janela atravessando meia-noite (ex: 22:00-08:00)
    return mins >= startMin || mins < endMin
}

// Formata data/hora do evento pra texto pt-BR
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 '' }
}

// Substitui variáveis no template
function renderTemplate(
    tpl: string,
    vars: { nome_paciente: string; data_sessao: string; hora_sessao: string; modalidade: string; nome_clinica: string }
): string {
    return tpl
        .replaceAll('{{nome_paciente}}', vars.nome_paciente)
        .replaceAll('{{data_sessao}}', vars.data_sessao)
        .replaceAll('{{hora_sessao}}', vars.hora_sessao)
        .replaceAll('{{modalidade}}', vars.modalidade)
        .replaceAll('{{nome_clinica}}', vars.nome_clinica)
}

// Envia via Evolution. Retorna messageId ou null se falhar.
async function sendViaEvolution(
    apiUrl: string, apiKey: string, instance: string, phone: string, text: string
): Promise<{ ok: boolean; messageId?: string; error?: 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(() => null) as Record<string, unknown> | null
        const msgId = (j?.key as { id?: string })?.id ?? null
        return { ok: true, messageId: msgId ?? undefined }
    } catch (err) {
        return { ok: false, error: String(err) }
    }
}

// Envia via Twilio. Retorna messageId + status ou erro.
async function sendViaTwilio(
    subSid: string, authToken: string, fromNumber: string, toPhone: string, text: string
): Promise<{ ok: boolean; messageId?: string; status?: string; error?: string }> {
    if (!subSid || !authToken || !fromNumber) {
        return { ok: false, error: 'Twilio credenciais incompletas' }
    }
    const toE164 = toPhone.startsWith('+') ? toPhone : `+${toPhone}`
    const endpoint = `https://api.twilio.com/2010-04-01/Accounts/${subSid}/Messages.json`
    const basicAuth = btoa(`${subSid}:${authToken}`)
    const params = new URLSearchParams()
    params.append('From', `whatsapp:${fromNumber}`)
    params.append('To', `whatsapp:${toE164}`)
    params.append('Body', text)
    try {
        const resp = await fetch(endpoint, {
            method: 'POST',
            headers: { 'Authorization': `Basic ${basicAuth}`, 'Content-Type': 'application/x-www-form-urlencoded' },
            body: params.toString()
        })
        const data = await resp.json().catch(() => null) as Record<string, unknown> | null
        if (!resp.ok) {
            return { ok: false, error: `Twilio ${resp.status}: ${(data?.message as string) || JSON.stringify(data).slice(0, 200)}` }
        }
        return { ok: true, messageId: String(data?.sid || ''), status: String(data?.status || 'queued') }
    } catch (e) {
        return { ok: false, error: String(e) }
    }
}

// Verifica se paciente está opted-out
async function isOptedOut(tdb: SupabaseClient, phone: string): Promise<boolean> {
    const { data } = await tdb
        .from('conversation_optouts')
        .select('id')
        .eq('phone', phone)
        .is('opted_back_in_at', null)
        .limit(1)
        .maybeSingle()
    return !!data
}

type ProcessStats = {
    considered: number
    sent: number
    skipped: Record<string, number>
    errors: number
}

// Processa eventos em uma janela especifica (já escopado a um tenant via tdb)
async function processWindow(
    tdb: SupabaseClient,
    admin: SupabaseClient,
    tenantId: string,
    tenantName: string,
    type: '24h' | '2h',
    minutesAhead: number,
    stats: ProcessStats
): Promise<void> {
    const windowMin = 15 // ±15min
    const start = new Date(Date.now() + (minutesAhead - windowMin) * 60 * 1000).toISOString()
    const end = new Date(Date.now() + (minutesAhead + windowMin) * 60 * 1000).toISOString()

    // Busca eventos na janela com patient (tenant tables via tdb; schema já filtra o tenant)
    const { data: events, error } = await tdb
        .from('agenda_eventos')
        .select(`
            id, inicio_em, modalidade, patient_id, status,
            patients:patient_id (id, nome_completo, telefone)
        `)
        .eq('status', 'agendado')
        .gte('inicio_em', start)
        .lte('inicio_em', end)

    if (error) {
        console.error('[reminders] events query error:', error.message)
        return
    }

    stats.considered += (events || []).length

    for (const ev of events || []) {
        try {
            const eventId = ev.id as string
            const pat = Array.isArray(ev.patients) ? ev.patients[0] : ev.patients
            if (!pat || !pat.telefone) {
                // Sem telefone — loga e pula
                await logSkip(tdb, eventId, type, 'no_phone')
                stats.skipped.no_phone = (stats.skipped.no_phone || 0) + 1
                continue
            }
            const phone = normalizePhoneBR(pat.telefone)
            if (!/^\d{10,15}$/.test(phone)) {
                await logSkip(tdb, eventId, type, 'invalid_phone')
                stats.skipped.invalid_phone = (stats.skipped.invalid_phone || 0) + 1
                continue
            }

            // Ja enviado? (UNIQUE constraint previne dup mas checamos pra economizar)
            const { data: existing } = await tdb
                .from('session_reminder_logs')
                .select('id')
                .eq('event_id', eventId)
                .eq('reminder_type', type)
                .maybeSingle()
            if (existing) {
                stats.skipped.already_sent = (stats.skipped.already_sent || 0) + 1
                continue
            }

            // Settings do tenant (tabela tenant; uma linha por schema)
            const { data: settings } = await tdb
                .from('session_reminder_settings')
                .select('*')
                .maybeSingle()

            if (!settings || !settings.enabled) {
                stats.skipped.disabled = (stats.skipped.disabled || 0) + 1
                continue
            }
            if (type === '24h' && !settings.send_24h) {
                stats.skipped.type_disabled = (stats.skipped.type_disabled || 0) + 1
                continue
            }
            if (type === '2h' && !settings.send_2h) {
                stats.skipped.type_disabled = (stats.skipped.type_disabled || 0) + 1
                continue
            }

            // Quiet hours
            if (settings.quiet_hours_enabled) {
                const startHHMM = String(settings.quiet_hours_start || '22:00').slice(0, 5)
                const endHHMM = String(settings.quiet_hours_end || '08:00').slice(0, 5)
                if (isQuietHoursNow(startHHMM, endHHMM)) {
                    await logSkip(tdb, eventId, type, 'quiet_hours')
                    stats.skipped.quiet_hours = (stats.skipped.quiet_hours || 0) + 1
                    continue
                }
            }

            // Opt-out
            if (settings.respect_opt_out && await isOptedOut(tdb, phone)) {
                await logSkip(tdb, eventId, type, 'opted_out')
                stats.skipped.opted_out = (stats.skipped.opted_out || 0) + 1
                continue
            }

            // Canal ativo
            const { data: channel } = await tdb
                .from('notification_channels')
                .select('provider, credentials, twilio_phone_number, is_active')
                .eq('channel', 'whatsapp')
                .is('deleted_at', null)
                .maybeSingle()
            if (!channel || !channel.is_active) {
                await logSkip(tdb, eventId, type, 'no_channel')
                stats.skipped.no_channel = (stats.skipped.no_channel || 0) + 1
                continue
            }

            // Monta mensagem (nome da clínica vem do tenant global, resolvido no loop)
            const tpl = type === '24h' ? settings.template_24h : settings.template_2h
            const text = renderTemplate(tpl, {
                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: tenantName || ''
            })

            // Envia (Evolution only por enquanto)
            // Aceita 'evolution' (legado) e 'evolution_api' (DB atual)
            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) {
                    await logSkip(tdb, eventId, type, 'creds_missing')
                    stats.skipped.creds_missing = (stats.skipped.creds_missing || 0) + 1
                    continue
                }
                const sendRes = await sendViaEvolution(creds.api_url, creds.api_key, creds.instance_name, phone, text)
                if (!sendRes.ok) {
                    console.error('[reminders] send failed for event', eventId, sendRes.error)
                    await tdb.from('session_reminder_logs').insert({
                        event_id: eventId, reminder_type: type,
                        provider: 'evolution', skip_reason: `send_failed: ${sendRes.error}`, to_phone: phone
                    })
                    stats.errors++
                    continue
                }
                // Registra outbound message + log
                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: type, event_id: eventId },
                    kanban_status: 'awaiting_patient',
                    responded_at: new Date().toISOString()
                }).select('id').single()

                await tdb.from('session_reminder_logs').insert({
                    event_id: eventId, reminder_type: type,
                    provider: 'evolution', to_phone: phone,
                    provider_message_id: sendRes.messageId ?? null,
                    conversation_message_id: msg?.id ?? null
                })
                stats.sent++
            } else if (providerKind === 'twilio') {
                // Busca creds twilio (colunas dedicadas + credentials JSONB com auth_token)
                const { data: fullChannel } = await tdb
                    .from('notification_channels')
                    .select('twilio_subaccount_sid, twilio_phone_number, credentials')
                    .eq('channel', 'whatsapp')
                    .is('deleted_at', null)
                    .maybeSingle()
                const twCreds = (fullChannel?.credentials ?? {}) as Record<string, string>
                const subSid = fullChannel?.twilio_subaccount_sid as string
                const subToken = twCreds.subaccount_auth_token
                const twFrom = fullChannel?.twilio_phone_number as string

                if (!subSid || !subToken || !twFrom) {
                    await logSkip(tdb, eventId, type, 'twilio_creds_missing')
                    stats.skipped.twilio_creds_missing = (stats.skipped.twilio_creds_missing || 0) + 1
                    continue
                }

                // Deduz 1 crédito ANTES (atômico via RPC; whatsapp_credit_* é GLOBAL → admin)
                const { error: dedErr } = await admin.rpc('deduct_whatsapp_credits', {
                    p_tenant_id: tenantId,
                    p_amount: 1,
                    p_conversation_message_id: null,
                    p_note: `Lembrete sessão ${type}`
                })
                if (dedErr) {
                    const reason = String(dedErr.message || '').includes('insufficient_credits') ? 'insufficient_credits' : 'deduct_error'
                    await logSkip(tdb, eventId, type, reason)
                    stats.skipped[reason] = (stats.skipped[reason] || 0) + 1
                    continue
                }

                const sendRes = await sendViaTwilio(subSid, subToken, twFrom, phone, text)
                if (!sendRes.ok) {
                    // Refund (GLOBAL → admin)
                    await admin.rpc('add_whatsapp_credits', {
                        p_tenant_id: tenantId,
                        p_amount: 1,
                        p_kind: 'refund',
                        p_purchase_id: null,
                        p_admin_id: null,
                        p_note: `Refund lembrete falhou: ${sendRes.error?.slice(0, 200)}`
                    })
                    console.error('[reminders] twilio send failed:', sendRes.error)
                    await tdb.from('session_reminder_logs').insert({
                        event_id: eventId, reminder_type: type,
                        provider: 'twilio', skip_reason: `send_failed: ${sendRes.error}`, to_phone: phone
                    })
                    stats.errors++
                    continue
                }

                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: 'twilio',
                    provider_message_id: sendRes.messageId ?? null,
                    provider_raw: { reminder_type: type, event_id: eventId, status: sendRes.status },
                    kanban_status: 'awaiting_patient',
                    responded_at: new Date().toISOString(),
                    delivery_status: sendRes.status === 'delivered' ? 'delivered' : 'sent'
                }).select('id').single()

                await tdb.from('session_reminder_logs').insert({
                    event_id: eventId, reminder_type: type,
                    provider: 'twilio', to_phone: phone,
                    provider_message_id: sendRes.messageId ?? null,
                    conversation_message_id: msg?.id ?? null
                })
                stats.sent++
            } else {
                await logSkip(tdb, eventId, type, 'unknown_provider')
                stats.skipped.unknown_provider = (stats.skipped.unknown_provider || 0) + 1
            }
        } catch (err) {
            console.error('[reminders] event process error:', err)
            stats.errors++
        }
    }
}

async function logSkip(
    tdb: SupabaseClient, eventId: string, type: '24h' | '2h', reason: string
) {
    await tdb.from('session_reminder_logs').insert({
        event_id: eventId, reminder_type: type,
        provider: 'skipped', skip_reason: reason
    })
}

Deno.serve(async (req: Request) => {
    if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })

    try {
        const admin = adminClient()

        const stats: ProcessStats = { considered: 0, sent: 0, skipped: {}, errors: 0 }

        // Varre todos os tenants com schema provisionado
        for (const t of await listTenantSchemas(admin)) {
            const tdb = admin.schema(t.schema)

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

            // 24h antes
            await processWindow(tdb, admin, t.tenantId, tenantName, '24h', 24 * 60, stats)
            // 2h antes
            await processWindow(tdb, admin, t.tenantId, tenantName, '2h', 2 * 60, stats)
        }

        return json({ ok: true, stats })
    } catch (err) {
        console.error('[reminders] fatal:', err)
        return json({ ok: false, error: String(err) }, 500)
    }
})
