const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const { authenticateToken: auth, requireManager } = require('../middleware/auth');
const { Payment, MonthlyDraw, ChitGroup, GroupMember, User, Notification } = require('../models');
const WhatsAppHelper = require('../utils/whatsapp-helper');
const { resolvePublicBaseUrl } = require('../utils/public-base-url');

/**
 * @route   POST /api/share/payment-receipt
 * @desc    Generate WhatsApp share link for payment receipt
 * @access  Private
 */
router.post('/payment-receipt', auth, async (req, res) => {
  try {
    const { paymentId } = req.body;

    if (!paymentId) {
      return res.status(400).json({
        success: false,
        message: 'Payment ID is required'
      });
    }

    // Get payment with referenced records (Sequelize)
    const payment = await Payment.findByPk(paymentId, {
      include: [
        { model: User, attributes: ['id', 'full_name', 'mobile_number'] },
        { model: ChitGroup, attributes: ['id', 'name', 'manager_id'] }
      ]
    });

    if (!payment) {
      return res.status(404).json({
        success: false,
        message: 'Payment not found'
      });
    }

    // Check authorization
    if (payment.user_id !== req.user.id && req.user.role !== 'manager') {
      return res.status(403).json({
        success: false,
        message: 'Not authorized'
      });
    }

    // Generate WhatsApp message
    const message = WhatsAppHelper.generatePaymentReceipt(
      payment,
      payment.ChitGroup,
      payment.User
    );

    // Generate WhatsApp link
    const whatsappUrl = WhatsAppHelper.generateShareLink(
      payment.User.mobile_number,
      message
    );

    // Log the share action
    await Notification.create({
      type: 'payment_confirmation',
      user_id: payment.user_id,
      group_id: payment.group_id,
      payment_id: payment.id,
      channel: 'whatsapp',
      message: message,
      status: 'sent'
    });

    res.json({
      success: true,
      data: {
        whatsappUrl,
        message,
        recipient: {
          name: payment.User.full_name,
          mobile: payment.User.mobile_number
        }
      }
    });
  } catch (error) {
    console.error('Error generating payment receipt share:', error);
    res.status(500).json({
      success: false,
      message: 'Server error'
    });
  }
});

/**
 * @route   POST /api/share/draw-link
 * @desc    Generate tokenized share link for draw result (WhatsApp-friendly)
 * @access  Private (Manager only)
 */
router.post('/draw-link', auth, requireManager, async (req, res) => {
  try {
    const { drawId } = req.body;

    if (!drawId) {
      return res.status(400).json({
        success: false,
        message: 'Draw ID is required'
      });
    }

    const draw = await MonthlyDraw.findByPk(drawId, {
      include: [
        { model: ChitGroup, attributes: ['id', 'name', 'manager_id'] },
        { model: User, as: 'winner', attributes: ['id', 'full_name', 'mobile_number'] }
      ]
    });

    if (!draw) {
      return res.status(404).json({
        success: false,
        message: 'Draw not found'
      });
    }

    if (!draw.ChitGroup || draw.ChitGroup.manager_id !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: 'Only the group manager can create share links for this draw'
      });
    }

    const totalMembers = await GroupMember.count({
      where: { group_id: draw.group_id, status: 'active' }
    });

    const shareSecret = process.env.SHARE_TOKEN_SECRET || process.env.JWT_SECRET;
    if (!shareSecret) {
      return res.status(500).json({
        success: false,
        message: 'Share token secret not configured'
      });
    }

    // Permanent signed links (no JWT expiry) so results stay openable anytime, unless overridden.
    const permanentLinks = String(process.env.SHARE_DRAW_PERMANENT_LINKS ?? 'true').toLowerCase() === 'true';
    const tokenTtlDays = Number.parseInt(process.env.SHARE_TOKEN_TTL_DAYS || '0', 10);
    const signOpts =
      permanentLinks || tokenTtlDays <= 0
        ? {}
        : { expiresIn: `${tokenTtlDays}d` };
    const token = jwt.sign(
      { type: 'draw_result', drawId: draw.id, groupId: draw.group_id },
      shareSecret,
      signOpts
    );

    const publicBaseUrl = resolvePublicBaseUrl(req);
    if (!publicBaseUrl) {
      return res.status(500).json({
        success: false,
        message:
          'PUBLIC_BASE_URL not configured (set to your site origin without /api, e.g. https://chitfund.deepteklabs.com)'
      });
    }
    // Query param keeps URL path short (avoids ENAMETOOLONG / static-file lookup on long JWT paths).
    const shareUrl = `${publicBaseUrl}/share/draw?t=${encodeURIComponent(token)}`;

    const message = WhatsAppHelper.generateDrawResult(
      draw.ChitGroup,
      draw.winner,
      draw.prize_amount,
      `${draw.month}/${draw.year}`,
      totalMembers
    ) + `\n\nView result: ${shareUrl}`;

    res.json({
      success: true,
      data: {
        shareUrl,
        message,
        draw: {
          month: draw.month,
          year: draw.year,
          winner: draw.winner ? draw.winner.full_name : null,
          prize: draw.prize_amount
        }
      }
    });
  } catch (error) {
    console.error('Error generating draw link:', error);
    res.status(500).json({
      success: false,
      message: 'Server error'
    });
  }
});

/**
 * @route   POST /api/share/group-invite
 * @desc    Generate WhatsApp share link for group invitation
 * @access  Private (Manager only)
 */
router.post('/group-invite', auth, async (req, res) => {
  try {
    const { groupId, recipientPhone } = req.body;

    if (!groupId || !recipientPhone) {
      return res.status(400).json({
        success: false,
        message: 'Group ID and recipient phone are required'
      });
    }

    // Get group
    const group = await ChitGroup.findByPk(groupId);

    if (!group) {
      return res.status(404).json({
        success: false,
        message: 'Group not found'
      });
    }

    // Check if user is manager of this group
    if (group.manager_id !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: 'Only group manager can send invitations'
      });
    }

    // Get manager details
    const manager = await User.findByPk(req.user.id);

    // Get current member count
    const currentMembers = await GroupMember.count({ where: { group_id: group.id } });

    group.current_members = currentMembers;

    // Generate WhatsApp message
    const appLink = process.env.APP_DOWNLOAD_LINK || 'Coming soon!';
    const message = WhatsAppHelper.generateGroupInvite(
      group,
      manager.full_name,
      appLink
    );

    // Generate WhatsApp link
    const whatsappUrl = WhatsAppHelper.generateShareLink(
      recipientPhone,
      message
    );

    // Log invitation
    await Notification.create({
      type: 'group_invite',
      user_id: req.user.id,
      group_id: group.id,
      channel: 'whatsapp',
      message: message,
      status: 'sent',
      metadata: {
        recipient_phone: recipientPhone
      }
    });

    res.json({
      success: true,
      data: {
        whatsappUrl,
        message,
        group: {
          name: group.name,
          monthly_installment: group.monthly_installment,
          duration_months: group.duration_months
        }
      }
    });
  } catch (error) {
    console.error('Error generating group invite share:', error);
    res.status(500).json({
      success: false,
      message: 'Server error'
    });
  }
});

/**
 * @route   POST /api/share/payment-reminder
 * @desc    Generate WhatsApp link for payment reminder (Manager)
 * @access  Private (Manager only)
 */
router.post('/payment-reminder', auth, async (req, res) => {
  try {
    const { groupId, memberId } = req.body;

    if (!groupId || !memberId) {
      return res.status(400).json({
        success: false,
        message: 'Group ID and Member ID are required'
      });
    }

    // Get group
    const group = await ChitGroup.findByPk(groupId);
    if (!group) {
      return res.status(404).json({
        success: false,
        message: 'Group not found'
      });
    }

    // Check authorization
    if (group.manager_id !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: 'Only group manager can send reminders'
      });
    }

    // Get member
    const member = await User.findByPk(memberId);
    if (!member) {
      return res.status(404).json({
        success: false,
        message: 'Member not found'
      });
    }

    // Calculate current month and due date
    const ReminderService = require('../services/reminder-service');
    const currentMonth = ReminderService.getCurrentMonthNumber(group);
    const dueDate = ReminderService.calculateDueDate(group, currentMonth);
    const daysLeft = WhatsAppHelper.getDaysUntil(dueDate.toDate());

    // Generate reminder message
    const message = WhatsAppHelper.generatePaymentReminder(
      member,
      group,
      dueDate.toDate(),
      group.monthly_installment,
      daysLeft
    );

    // Generate WhatsApp link
    const whatsappUrl = WhatsAppHelper.generateShareLink(
      member.mobile_number,
      message
    );

    // Log reminder
    await Notification.create({
      type: 'payment_reminder',
      user_id: member.id,
      group_id: group.id,
      channel: 'whatsapp',
      message: message,
      days_before_due: daysLeft,
      status: 'sent'
    });

    res.json({
      success: true,
      data: {
        whatsappUrl,
        message,
        member: {
          name: member.full_name,
          mobile: member.mobile_number
        },
        payment_due: {
          amount: group.monthly_installment,
          due_date: dueDate.format('DD MMM YYYY'),
          days_left: daysLeft
        }
      }
    });
  } catch (error) {
    console.error('Error generating payment reminder:', error);
    res.status(500).json({
      success: false,
      message: 'Server error'
    });
  }
});

/**
 * @route   POST /api/share/bulk-reminders
 * @desc    Generate bulk WhatsApp reminders for all unpaid members
 * @access  Private (Manager only)
 */
router.post('/bulk-reminders', auth, async (req, res) => {
  try {
    const { groupId } = req.body;

    if (!groupId) {
      return res.status(400).json({
        success: false,
        message: 'Group ID is required'
      });
    }

    // Get group
    const group = await ChitGroup.findByPk(groupId);
    if (!group) {
      return res.status(404).json({
        success: false,
        message: 'Group not found'
      });
    }

    // Check authorization
    if (group.manager_id !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: 'Only group manager can send reminders'
      });
    }

    // Get reminder service
    const ReminderService = require('../services/reminder-service');
    const currentMonth = ReminderService.getCurrentMonthNumber(group);
    const dueDate = ReminderService.calculateDueDate(group, currentMonth);
    const daysLeft = WhatsAppHelper.getDaysUntil(dueDate.toDate());

    // Get all unpaid members
    const members = await GroupMember.findAll({
      where: { group_id: group.id, status: 'active' },
      include: [{ model: User, attributes: ['id', 'full_name', 'mobile_number'] }]
    });

    const reminders = [];

    for (const member of members) {
      // Check if paid
      const payment = await Payment.findOne({
        where: {
          group_id: group.id,
          user_id: member.user_id,
          month: currentMonth,
          year: new Date().getFullYear(),
          status: 'success'
        }
      });

      if (!payment) {
        // Generate reminder
        const message = WhatsAppHelper.generatePaymentReminder(
          member.user_id,
          group,
          dueDate.toDate(),
          group.monthly_installment,
          daysLeft
        );

        const whatsappUrl = WhatsAppHelper.generateShareLink(
          member.User.mobile_number,
          message
        );

        reminders.push({
          member: {
            id: member.User.id,
            name: member.User.full_name,
            mobile: member.User.mobile_number
          },
          whatsappUrl
        });

        // Log notification
        await Notification.create({
          type: 'payment_reminder',
          user_id: member.User.id,
          group_id: group.id,
          channel: 'whatsapp',
          message: message,
          days_before_due: daysLeft,
          status: 'sent'
        });
      }
    }

    res.json({
      success: true,
      message: `Generated ${reminders.length} reminder(s)`,
      data: {
        total_reminders: reminders.length,
        reminders: reminders
      }
    });
  } catch (error) {
    console.error('Error generating bulk reminders:', error);
    res.status(500).json({
      success: false,
      message: 'Server error'
    });
  }
});

module.exports = router;

