/* eslint-disable camelcase */
const NotificationModel = require('../../../models/NotificationModel')
const PostModel = require('../../../models/PostModel')
const UserModel = require('../../../models/UserModel')
const jMoment = require('moment-jalaali')
const { default: mongoose } = require('mongoose')

const getPosts = async (req, res, next) => {
  try {
    const authHeader = req.header('Authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({ message: 'Access Denied: No token provided' });
    }
    const token = authHeader.split(' ')[1];

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

    const filter = {};
    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: 'user_id',
        select: '_id user_name first_name mobile last_name national_code user_type expertise',
      },
    };

    const posts = await PostModel.paginate(filter, options);
    const postList = posts.docs.map((post) => ({
      _id: post._id,
      post_image: post.post_images && post.post_images.length > 0 ? post.post_images[0] : post.post_video || null, // استفاده از اولین تصویر یا ویدئو
      status: post.status,
      post_images: post.post_images,
      post_video: post.post_video,
      type: post.type,
      files: post.files,
      user_id: post.user_id?._id || null,
      user_name: post.user_id?.user_name || '-',
      user_type: post.user_id?.user_type || '-',
      expertise: post.user_id?.expertise || '-',
      first_name: post.user_id?.first_name || '-',
      last_name: post.user_id?.last_name || '-',
      mobile: post.user_id?.mobile || '-',
      national_code: post.user_id?.national_code || '-',
      createdAt: post.createdAt ? jMoment(post.createdAt).format('jYYYY-jMM-jDD HH:mm') : '-',
    }));

    res.status(200).json({
      posts: postList,
      totalPages: posts.totalPages,
      totalItems: posts.totalDocs,
    });
  } catch (error) {
    console.error('Error in getPosts:', error);
    res.status(500).json({ message: 'خطا در دریافت پست‌ها.' });
  }
};
const getPostDetail = async (req, res, next) => {
  try {
    const token = req.header('Authorization').split(' ')[1]
    if (!token) return res.status(401).send('Access Denied')
    const post_id = req.query.post_id
    // eslint-disable-next-line no-unused-vars

    if (!mongoose.Types.ObjectId.isValid(post_id)) {
      return res.status(400).json({ message: 'شناسه پست معتبر نیست' })
    }
    const post = await PostModel.findById(post_id).populate('user_id', '_id user_name first_name last_name profile_image user_level')

    if (!post) {
      return res.status(404).json({ message: 'پست مورد نظر یافت نشد' })
    }
    const response = {
      _id: post._id,
      post_image: post.post_images && post.post_images.length > 0 ? post.post_images[0] : post.post_video || null, // استفاده از اولین تصویر یا ویدئو
      status: post.status,
      caption: post.caption,
      comments: post.comments,
      post_images: post.post_images,
      post_video: post.post_video,
      type: post.type,
      files: post.files,
      user_id: post.user_id?._id || null,
      user_name: post.user_id?.user_name || '-',
      user_type: post.user_id?.user_type || '-',
      expertise: post.user_id?.expertise || '-',
      first_name: post.user_id?.first_name || '-',
      last_name: post.user_id?.last_name || '-',
      mobile: post.user_id?.mobile || '-',
      national_code: post.user_id?.national_code || '-',
      createdAt: post.createdAt ? jMoment(post.createdAt).format('jYYYY-jMM-jDD HH:mm') : '-',
    }
    return res.status(200).json({ post: response })
  } catch (error) {
    next(error)
  }
}

const acceptPost = async (req, res, next) => {
  try {
    const token = req.header('Authorization').split(' ')[1]
    if (!token) return res.status(401).send('Access Denied')

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

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

    const user = await UserModel.findById(user_id)
    const post = await PostModel.findById(id)

    if (!post) {
      return res.status(404).json({
        error: true,
        message: 'پست مورد نظر یافت نشد'
      })
    }

    post.status = status
    await post.save()
    if (status === 'accept') {
      user.last_post = post
      await user.save()

      const notification = new NotificationModel({
        user_id: user?._id,
        project_post_id: post?._id,
        type: 'accept-post',
        title: 'انتشار پست',
        description: 'پست شما مورد تایید قرار گرفت.'
      })
      await notification.save()
    } else {
      const notification = new NotificationModel({
        user_id: user?._id,
        project_post_id: post?._id,
        type: 'reject-post',
        title: 'رد پست',
        description: 'پست شما مورد تایید قرار نگرفت.'
      })
      await notification.save()
    }

    res.status(201).json({ message: 'پست با موفقیت تایید شد' })
  } catch (error) {
    next(error)
  }
}

module.exports = {
  acceptPost, getPosts, getPostDetail
}
