/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * LOOPUMAN NOTIFICATION SERVICE
 * 13th January 2026
 * ═══════════════════════════════════════════════════════════════════════════════
 * 
 * Handles all notifications to users via Telegram.
 * 
 * NOTIFICATION TYPES:
 * - Payment received
 * - Task completed
 * - Task approved/rejected
 * - Milestone achieved
 * - Dispute updates
 * - Withdrawal processed
 * - Referral bonus earned
 * 
 * ═══════════════════════════════════════════════════════════════════════════════
 */

'use strict';

const { createClient } = require('@supabase/supabase-js');

const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_KEY);

let telegramBot = null;

/**
 * Set Telegram bot reference
 */
function setBot(bot) {
  telegramBot = bot;
}

/**
 * Send notification to user by user ID
 */
async function notify(userId, message, options = {}) {
  if (!telegramBot) {
    console.log('No Telegram bot configured');
    return false;
  }
  
  try {
    // Get user's Telegram ID
    const { data: user } = await supabase
      .from('app_users')
      .select('telegram_id')
      .eq('id', userId)
      .single();
    
    if (!user?.telegram_id) {
      console.log(`No Telegram ID for user ${userId}`);
      return false;
    }
    
    await telegramBot.telegram.sendMessage(user.telegram_id, message, {
      parse_mode: 'Markdown',
      ...options
    });
    
    return true;
  } catch (error) {
    console.error('Notification failed:', error.message);
    return false;
  }
}

/**
 * Notify worker of task approval
 */
async function notifyTaskApproved(workerId, task, payment) {
  const message = 
    `✅ *Task Approved!*\n\n` +
    `📋 *Task:* ${task.title}\n` +
    `💰 *Earned:* Ⓥ${payment.toLocaleString()} ($${(payment/100).toFixed(2)})\n\n` +
    `Great work! Payment added to your earnings.`;
  
  await notify(workerId, message, {
    reply_markup: {
      inline_keyboard: [
        [{ text: '💰 View Balance', callback_data: 'view_balance' }],
        [{ text: '📋 Find More Tasks', callback_data: 'browse_tasks' }]
      ]
    }
  });
}

/**
 * Notify worker of task rejection
 */
async function notifyTaskRejected(workerId, task, reason) {
  const message = 
    `❌ *Task Rejected*\n\n` +
    `📋 *Task:* ${task.title}\n` +
    `📝 *Reason:* ${reason || 'Quality requirements not met'}\n\n` +
    `You can dispute this decision if you believe it's unfair.`;
  
  await notify(workerId, message, {
    reply_markup: {
      inline_keyboard: [
        [{ text: '⚠️ File Dispute', callback_data: `dispute_${task.id}` }],
        [{ text: '📋 Find Other Tasks', callback_data: 'browse_tasks' }]
      ]
    }
  });
}

/**
 * Notify requester of task completion
 */
async function notifyTaskSubmitted(requesterId, task, worker) {
  const workerId = worker.id ? worker.id.slice(-6).toUpperCase() : 'Worker';
  const message = 
    `📬 *New Submission!*\n\n` +
    `📋 *Task:* ${task.title}\n` +
    `👤 *Worker:* #${workerId}\n` +
    `⭐ *Rating:* ${worker.average_rating}/5.0\n\n` +
    `Review and approve/reject the submission.`;
  
  await notify(requesterId, message, {
    reply_markup: {
      inline_keyboard: [
        [{ text: '👀 Review Submission', callback_data: `review_${task.id}` }]
      ]
    }
  });
}

/**
 * Notify user of milestone achieved
 */
async function notifyMilestone(userId, milestone, txHash = null) {
  let message = 
    `🎉 *Achievement Unlocked!*\n\n` +
    `${milestone.emoji} *${milestone.badge}*\n\n` +
    `Congratulations! You've completed ${milestone.tasks} tasks.`;
  
  if (txHash) {
    message += `\n\n🔗 [View on CeloScan](https://celoscan.io/tx/${txHash})`;
  }
  
  await notify(userId, message);
}

/**
 * Notify user of withdrawal processed
 */
async function notifyWithdrawal(userId, amount, txHash, currency) {
  const message = 
    `💸 *Withdrawal Complete!*\n\n` +
    `💰 *Amount:* Ⓥ${amount.toLocaleString()} ($${(amount/100).toFixed(2)})\n` +
    `💱 *Currency:* ${currency}\n` +
    `📜 *TX:* [View on CeloScan](https://celoscan.io/tx/${txHash})\n\n` +
    `Funds sent to your wallet!`;
  
  await notify(userId, message);
}

/**
 * Notify referrer of bonus earned
 */
async function notifyReferralBonus(referrerId, bonus, refereeName) {
  const message = 
    `🔗 *Referral Bonus!*\n\n` +
    `Your referral completed a task.\n` +
    `💰 *Bonus:* Ⓥ${bonus} (1%)\n\n` +
    `_Keep sharing to earn more!_`;
  
  await notify(referrerId, message);
}

/**
 * Notify user of dispute update
 */
async function notifyDisputeUpdate(userId, dispute, update) {
  const message = 
    `⚖️ *Dispute Update*\n\n` +
    `📋 *Task:* ${dispute.task_title || 'Task'}\n` +
    `📝 *Status:* ${update.status}\n` +
    `💬 *Message:* ${update.message}\n\n`;
  
  await notify(userId, message);
}

/**
 * Send admin alert
 */
async function alertAdmin(level, message, details = {}) {
  const adminIds = (process.env.ADMIN_TELEGRAM_IDS || '').split(',').filter(Boolean);
  
  if (!telegramBot || adminIds.length === 0) return;
  
  const emoji = level === 'critical' ? '🚨' : level === 'warning' ? '⚠️' : 'ℹ️';
  
  const text = 
    `${emoji} *ADMIN ALERT*\n\n` +
    `*Level:* ${level.toUpperCase()}\n` +
    `*Message:* ${message}\n` +
    (Object.keys(details).length > 0 ? `*Details:* ${JSON.stringify(details, null, 2)}` : '');
  
  for (const adminId of adminIds) {
    try {
      await telegramBot.telegram.sendMessage(adminId, text, { parse_mode: 'Markdown' });
    } catch (error) {
      console.error(`Failed to alert admin ${adminId}:`, error.message);
    }
  }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EXPORTS
// ═══════════════════════════════════════════════════════════════════════════════

module.exports = {
  setBot,
  notify,
  notifyTaskApproved,
  notifyTaskRejected,
  notifyTaskSubmitted,
  notifyMilestone,
  notifyWithdrawal,
  notifyReferralBonus,
  notifyDisputeUpdate,
  alertAdmin
};
