const jwt = require('jsonwebtoken')
const PaymentModel = require('../../../models/PaymentModel')
const ProjectModel = require('../../../models/ProjectModel')
const moment = require('moment-jalaali')

const getFinancial = async (req, res) => {
  try {
    // Extract user ID from JWT token
    const token = req.header('Authorization').split(' ')[1]
    if (!token) return res.status(401).send('Access Denied')
    const decodedToken = jwt.verify(token, process.env.APP_SECRET)
    const userId = decodedToken.id
    const options = {
      page: req.query.page || 1, // صفحه پیش‌فرض ۱
      limit: req.query.limit || 10, // حداکثر تعداد موارد برای هر صفحه
      sort: { createdAt: -1 }
    }
    // Find all payments associated with the user
    const financial = await PaymentModel.paginate(
      { user_id: userId }, // فیلتر
      options // گزینه‌های پیجینیشن
    )
    // Prepare the data to be sent back
    const userPayments = await Promise.all(financial.docs.map(async (payment) => {
      // Find the project associated with the payment
      const project = await ProjectModel.findById(payment.project_id)

      if (!project) {
        return null
      }
      // استفاده از کتابخانه moment-jalaali برای تبدیل تاریخ و زمان به شمسی
      const shamsiDate = moment(payment.createdAt).format('jYYYY-jMM-jDD')
      const shamsiTime = moment(payment.createdAt).format('HH:mm')

      // Extract the required information
      const userPayment = {
        _id: payment._id,
        project_title: project.title,
        project_id: project._id,
        payment_date: shamsiDate, // Format date as YYYY-MM-DD
        payment_time: shamsiTime,
        iban: project.creator_id ? project.creator_id.iban : null, // Check if creator_id exists before accessing iban
        amount: payment.amount,
        payment_status: payment.status
      }

      return userPayment
    }))

    // Filter out null values
    const validUserPayments = userPayments.filter(payment => payment !== null)

    // Send the payments back to the client
    res.status(200).json({
      financial:  financial,
      totalPages: financial.totalPages, // ارسال تعداد کل صفحات
      totalItems: financial.totalDocs // ارسال تعداد کل آیتم‌ها
    })
  } catch (error) {
    console.error('Error occurred:', error)
    res.status(500).json({ error: 'Internal server error' })
  }
}

module.exports = { getFinancial }
