const PhonePeTransactionSyncService = require('../services/phonepe-transaction-sync-service');
const { ChitGroup, GroupMember, User, Payment } = require('../models');
const { Op } = require('sequelize');

/**
 * Sync PhonePe transactions for a manager
 */
const syncTransactions = async (req, res) => {
  try {
    const managerId = req.user.id;
    const { days_back } = req.body;
    const daysBack = days_back || 7;

    console.log(`Syncing transactions for manager ${managerId}, last ${daysBack} days`);

    const syncService = new PhonePeTransactionSyncService();
    const result = await syncService.syncTransactionsForManager(managerId, daysBack);

    if (result.success) {
      return res.json({
        success: true,
        message: 'Transactions synced successfully',
        data: result.results,
      });
    } else {
      return res.status(400).json({
        success: false,
        message: result.message || 'Failed to sync transactions',
      });
    }
  } catch (error) {
    console.error('Sync transactions error:', error);
    return res.status(500).json({
      success: false,
      message: 'Failed to sync transactions',
    });
  }
};

/**
 * Get transactions that need manual review
 */
const getReviewQueue = async (req, res) => {
  try {
    const managerId = req.user.id;

    const syncService = new PhonePeTransactionSyncService();
    const result = await syncService.getTransactionsNeedingReview(managerId);

    if (result.success) {
      return res.json({
        success: true,
        data: {
          review_queue: result.reviewQueue,
          count: result.count,
        },
      });
    } else {
      return res.status(400).json({
        success: false,
        message: result.message || 'Failed to get review queue',
      });
    }
  } catch (error) {
    console.error('Get review queue error:', error);
    return res.status(500).json({
      success: false,
      message: 'Failed to get review queue',
    });
  }
};

/**
 * Approve a suggested payment match
 */
const approveSuggestedMatch = async (req, res) => {
  try {
    const managerId = req.user.id;
    const {
      transaction_id,
      group_id,
      user_id,
      month,
      year,
      amount,
    } = req.body;

    // Validate manager owns the group
    const group = await ChitGroup.findOne({
      where: { id: group_id, manager_id: managerId },
    });

    if (!group) {
      return res.status(403).json({
        success: false,
        message: 'Access denied or group not found',
      });
    }

    // Validate member exists in group
    const member = await GroupMember.findOne({
      where: { group_id, user_id, status: 'active' },
    });

    if (!member) {
      return res.status(400).json({
        success: false,
        message: 'Member not found in this group',
      });
    }

    const syncService = new PhonePeTransactionSyncService();
    const result = await syncService.approveSuggestedMatch(
      transaction_id,
      group_id,
      user_id,
      month,
      year,
      amount
    );

    if (result.success) {
      return res.json({
        success: true,
        message: 'Payment recorded successfully',
        data: result.payment,
      });
    } else {
      return res.status(400).json({
        success: false,
        message: result.message,
      });
    }
  } catch (error) {
    console.error('Approve match error:', error);
    return res.status(500).json({
      success: false,
      message: 'Failed to approve match',
    });
  }
};

/**
 * Reject a suggested match
 */
const rejectSuggestedMatch = async (req, res) => {
  try {
    const { transaction_id, reason } = req.body;

    // Log rejection for future ML improvements
    console.log('Match rejected:', { transaction_id, reason });

    return res.json({
      success: true,
      message: 'Match rejected',
    });
  } catch (error) {
    console.error('Reject match error:', error);
    return res.status(500).json({
      success: false,
      message: 'Failed to reject match',
    });
  }
};

/**
 * Get sync history and stats
 */
const getSyncStats = async (req, res) => {
  try {
    const managerId = req.user.id;

    // Get groups for this manager
    const groups = await ChitGroup.findAll({
      where: { manager_id: managerId },
    });

    // Get auto-synced payments (last 30 days)
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const autoSyncedPayments = await Payment.count({
      where: {
        group_id: { [Op.in]: groups.map(g => g.id) },
        notes: { [Op.like]: '%Auto-synced from PhonePe%' },
        created_at: { [Op.gt]: thirtyDaysAgo },
      },
    });

    const pendingReviewCount = 0; // Would fetch from a review queue table if implemented

    return res.json({
      success: true,
      data: {
        total_groups: groups.length,
        auto_synced_payments_30d: autoSyncedPayments,
        pending_review: pendingReviewCount,
        last_sync: new Date(), // Would track in database
      },
    });
  } catch (error) {
    console.error('Get sync stats error:', error);
    return res.status(500).json({
      success: false,
      message: 'Failed to get sync stats',
    });
  }
};

module.exports = {
  syncTransactions,
  getReviewQueue,
  approveSuggestedMatch,
  rejectSuggestedMatch,
  getSyncStats,
};

