/* eslint-disable camelcase */
const AdvertisingComment = require('../../../models/AdvertisingCommentModel')
const jMoment = require('moment-jalaali')
const mongoose = require('mongoose')
const AdvertisingModel = require('../../../models/AdvertisingModel')
const NotificationModel = require('../../../models/NotificationModel')

// دریافت کامنت‌ها
const getAdvertisingComments = async (req, res, next) => {
  try {
    const token = req.header('Authorization').split(' ')[1]
    if (!token) return res.status(401).send('Access Denied')

    const {
      page = 1, limit = 10,
      startDate,
      endDate,
      status
    } = req.query
    const filter = {}

    // Date
    if (startDate || endDate) {
      filter.createdAt = {}

      if (startDate) {
        filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
      }

      if (endDate) {
        filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
      }
    }

    if (status) {
      filter.status = status
    }
    const options = {
      page: parseInt(page),
      limit: parseInt(limit),
      sort: { createdAt: -1 },
      populate: [
        { path: 'userId', select: 'user_name first_name last_name profile_image' },
        { path: 'advertisingId', select: 'title', populate: { path: 'creator_id', select: 'user_name first_name last_name' } }
        // اضافه کردن اطلاعات سازنده
      ]
    }

    const comments = await AdvertisingComment.paginate(filter, options)
    const commentList = comments.docs.map(comment => ({
      _id: comment._id,
      createdAt: jMoment(comment.createdAt).format('jYYYY-jMM-jDD HH:mm'),
      status: comment.status,
      text: comment.text,
      advertising: comment.advertisingId ? comment.advertisingId.title : null,
      user: comment.userId ? {
        _id: comment.userId._id,
        user_name: comment.userId.user_name,
        first_name: comment.userId.first_name,
        last_name: comment.userId.last_name,
        profile_image: comment.userId.profile_image
      } : null,
      creator: (comment.advertisingId && comment.advertisingId.creator_id) ? {
        _id: comment.advertisingId.creator_id._id,
        user_name: comment.advertisingId.creator_id.user_name,
        first_name: comment.advertisingId.creator_id.first_name,
        last_name: comment.advertisingId.creator_id.last_name
      } : null
    }));
    

    res.status(200).json({
      comments: commentList,
      totalPages: comments.totalPages,
      totalItems: comments.totalDocs
    })
  } catch (error) {
    next(error)
  }
}

// دریافت جزئیات یک کامنت
const getAdvertisingCommentDetail = async (req, res, next) => {
  try {
    const token = req.header('Authorization').split(' ')[1]
    if (!token) return res.status(401).send('Access Denied')

    const comment_id = req.query.comment_id

    if (!mongoose.Types.ObjectId.isValid(comment_id)) {
      return res.status(400).json({ message: 'شناسه کامنت معتبر نیست' })
    }

    const comment = await AdvertisingComment.findById(comment_id)
      .populate('userId', 'user_name first_name last_name profile_image')
      .populate({
        path: 'advertisingId',
        select: 'title creator_id',
        populate: {
          path: 'creator_id',
          select: 'user_name first_name last_name'
        }
      })
    if (!comment) {
      return res.status(404).json({ message: 'کامنت مورد نظر یافت نشد' })
    }

    const response = {
      _id: comment._id,
      text: comment.text,
      createdAt: jMoment(comment.createdAt).format('jYYYY-jMM-jDD HH:mm'),
      status: comment.status,
      advertising: comment.advertisingId ? comment.advertisingId.title : null,
      creator: {
        _id: comment?.advertisingId?.creator_id._id,
        user_name: comment?.advertisingId?.creator_id.user_name,
        first_name: comment?.advertisingId?.creator_id.first_name,
        last_name: comment?.advertisingId?.creator_id.last_name
      },
      user: {
        _id: comment.userId._id,
        user_name: comment.userId.user_name,
        first_name: comment.userId.first_name,
        last_name: comment.userId.last_name,
        profile_image: comment.userId.profile_image
      }
    }

    res.status(200).json({ comment: response })
  } catch (error) {
    next(error)
  }
}

// تایید یک کامنت
const acceptAdvertisingComment = async (req, res, next) => {
  try {
    const token = req.header('Authorization').split(' ')[1]
    if (!token) return res.status(401).send('Access Denied')

    const { id, status, text } = req.body

    if (!id || !status) {
      return res.status(422).json({
        error: true,
        message: 'اطلاعات ارسالی اشتباه است'
      })
    }

    const comment = await AdvertisingComment.findById(id)
    // افزایش تعداد کامنت‌های تبلیغ
    await AdvertisingModel.findByIdAndUpdate(comment?.advertisingId, { $inc: { commentsCount: 1 } })
    if (!comment) {
      return res.status(404).json({
        error: true,
        message: 'کامنت مورد نظر یافت نشد'
      })
    }

    if (text) {
      comment.text = text
    }
    comment.status = status
    await comment.save()

    if (status === 'accepted') {
      const notification = new NotificationModel({
        user_id: comment?.userId,
        project_post_id: comment?.advertisingId,
        type: 'vitrine-comment',
        title: 'انتشار نظر',
        description: 'نظر شما منتشر شد.'
      })
      await notification.save()
    } else {
      const notification = new NotificationModel({
        user_id: comment?.userId,
        project_post_id: comment?.advertisingId,
        type: 'vitrine-comment',
        title: 'رد نظر',
        description: 'نظر شما رد شد.'
      })
      await notification.save()
    }
    res.status(201).json({ message: 'کامنت با موفقیت تایید شد' })
  } catch (error) {
    next(error)
  }
}

module.exports = {
  getAdvertisingComments,
  getAdvertisingCommentDetail,
  acceptAdvertisingComment
}
