'use strict'

const { query, execute } = require('../database/postgres')
const ClubNotif = require('../services/clubNotificationService')

// ── Suspender inadimplentes (>5 dias) ────────────────────────────────────────

async function suspendOverdueMembers() {
  try {
    const rows = await query(
      `SELECT cm.id, cm.user_cpf, cm.user_nome, cm.user_telefone,
              bc.name AS club_name
       FROM club_members cm
       JOIN benefit_clubs bc ON bc.id = cm.club_id
       WHERE cm.status = 'active'
         AND cm.next_billing_at < NOW() - INTERVAL '5 days'`,
      []
    )
    for (const m of (rows || [])) {
      await execute(`UPDATE club_members SET status='suspended' WHERE id=$1`, [m.id])
      ClubNotif.notifySuspended(m.user_cpf, m.user_nome, m.user_telefone, m.club_name).catch(() => {})
    }
    if (rows?.length) console.log(`[clubWorker] ${rows.length} membro(s) suspenso(s) por inadimplência`)
  } catch (err) {
    console.error('[clubWorker] suspendOverdue:', err.message)
  }
}

// ── Lembrete de vencimento (3 dias antes) ────────────────────────────────────

async function sendPaymentReminders() {
  try {
    const rows = await query(
      `SELECT cm.id, cm.user_cpf, cm.user_nome, cm.user_telefone,
              cm.next_billing_at, bc.name AS club_name
       FROM club_members cm
       JOIN benefit_clubs bc ON bc.id = cm.club_id
       WHERE cm.status = 'active'
         AND cm.next_billing_at::date = (NOW() + INTERVAL '3 days')::date`,
      []
    )
    for (const m of (rows || [])) {
      const dueDate = new Date(m.next_billing_at).toLocaleDateString('pt-BR')
      ClubNotif.notifyPaymentReminder(
        m.user_cpf, m.user_nome, m.user_telefone, m.club_name, dueDate, null
      ).catch(() => {})
    }
    if (rows?.length) console.log(`[clubWorker] ${rows.length} lembrete(s) de vencimento enviado(s)`)
  } catch (err) {
    console.error('[clubWorker] paymentReminders:', err.message)
  }
}

// ── Iniciar workers com interval ─────────────────────────────────────────────

function startClubWorker() {
  // Roda na inicialização e depois a cada 6h
  const SIX_HOURS = 6 * 60 * 60 * 1000

  async function tick() {
    await suspendOverdueMembers()
    await sendPaymentReminders()
  }

  tick()
  setInterval(tick, SIX_HOURS)
  console.log('✅ Club worker iniciado (intervalo: 6h)')
}

module.exports = { startClubWorker, suspendOverdueMembers, sendPaymentReminders }
