/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * LOOPUMAN NOTIFICATION SERVICE
 * Fixed: 9 February 2026
 * ═══════════════════════════════════════════════════════════════════════════════
 *
 * Handles all notifications to users via Telegram.
 *
 * FIXES APPLIED:
 *  - Bug 1 (MEDIUM):  Markdown special characters now escaped in user content
 *  - Bug 3 (LOW):     Uses VAE_RATE constant instead of hardcoded /100
 *
 * ═══════════════════════════════════════════════════════════════════════════════
 */

'use strict';

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

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

const VAE_RATE = 100; // 100 VAE = $1 USD

let telegramBot = null;

/**
 * Escape Markdown V1 special characters in user-supplied strings.
 * Prevents task titles like "my_first_task" from breaking Telegram formatting.
 */
function escMd(text) {
  if (!text) return '';
  return String(text).replace(/([_*\[\]()~`>#+\-=|{}.!\\])/g, '\\$1');
}

/**
 * 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 usdAmount = (payment / VAE_RATE).toFixed(2);
  const message =
    `✅ *Task Approved\\!*\n\n` +
    `📋 *Task:* ${escMd(task.title)}\n` +
    `💰 *Earned:* Ⓥ${payment.toLocaleString('en-US')} \\($${usdAmount}\\)\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:* ${escMd(task.title)}\n` +
    `📝 *Reason:* ${escMd(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 username = worker.telegram_username ? `@${escMd(worker.telegram_username)}` : 'Anonymous';
  const message =
    `📬 *New Submission\\!*\n\n` +
    `📋 *Task:* ${escMd(task.title)}\n` +
    `👤 *Worker:* ${username}\n` +
    `⭐ *Rating:* ${worker.average_rating || 0}/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} *${escMd(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 usdAmount = (amount / VAE_RATE).toFixed(2);
  const message =
    `💸 *Withdrawal Complete\\!*\n\n` +
    `💰 *Amount:* Ⓥ${amount.toLocaleString('en-US')} \\($${usdAmount}\\)\n` +
    `💱 *Currency:* ${escMd(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:* ${escMd(dispute.task_title || 'Task')}\n` +
    `📝 *Status:* ${escMd(update.status)}\n` +
    `💬 *Message:* ${escMd(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 detailStr = Object.keys(details).length > 0
    ? `*Details:* \`${JSON.stringify(details)}\``
    : '';

  const text =
    `${emoji} *ADMIN ALERT*\n\n` +
    `*Level:* ${level.toUpperCase()}\n` +
    `*Message:* ${escMd(message)}\n` +
    detailStr;

  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
};
