const NotificationModel = require('../../../models/NotificationModel')
const TicketMessageModel = require('../../../models/TicketMessageModel')
const TicketModel = require('../../../models/TicketModel')
const jwt = require('jsonwebtoken')
const jMoment = require('moment-jalaali')

const getAllTickets = async (req, res) => {
  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, 10) || 1,
      limit: parseInt(limit, 10) || 10,
      populate: [
        { path: 'user', select: '_id user_name first_name last_name mobile expertise' }
      ],
      sort: { updatedAt: -1 }
    }
    const tickets = await TicketModel.paginate(filter, options)
    const ticketList = tickets?.docs.map(ticket => {
      const jDate = jMoment(ticket.createdAt).format('jYYYY-jMM-jDD HH:mm')
      return {
        ...ticket._doc,
        createdAt: jDate
      }
    })
    res.json({
      tickets: ticketList,
      totalPages: tickets.totalPages, // ارسال تعداد کل صفحات
      totalItems: tickets.totalDocs // ارسال تعداد کل آیتم‌ها
    })
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' })
  }
}
const addAdminMessageToTicket = async (req, res) => {
  try {
    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 adminId = decodedToken.id

    const { text, ticketId } = req.body

    const newMessage = new TicketMessageModel({
      text,
      senderType: 'Admin',
      senderId: adminId,
      ticket: ticketId
    })
    await newMessage.save()

    const ticket = await TicketModel.findById(ticketId)
    if (!ticket) {
      return res.status(404).json({ error: 'Ticket not found' })
    }
    ticket.status = 'Answered'
    ticket.new_message = true
    await ticket.save()
    const notification = new NotificationModel({
      user_id: ticket?.user,
      project_post_id: ticket?._id,
      type: 'ticket-message',
      title: 'پاسخ پشتیبانی',
      description: `پاسخ جدید در تیکت: ${ticket?.title}`
    })
    await notification.save()
    res.status(201).json(newMessage)
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' })
  }
}
// senderId
const getTicketMessages = async (req, res) => {
  try {
    const token = req.header('Authorization').split(' ')[1]
    if (!token) return res.status(401).send('Access Denied')
    const { ticketId } = req.query
    const { page = 1, limit = 10 } = req.query
    const options = {
      page: parseInt(page) || 1,
      limit: parseInt(limit) || 10,
      populate: [
        { path: 'senderId', select: '_id user_name first_name last_name mobile expertise' }
      ],
      sort: { createdAt: -1 }
    }
    const messages = await TicketMessageModel.paginate({ ticket: ticketId }, options)
    const messageList = messages?.docs.map(message => {
      const jDate = jMoment(message.createdAt).format('jYYYY-jMM-jDD HH:mm')
      return {
        ...message._doc,
        createdAt: jDate
      }
    })
    res.json({
      messages: messageList.reverse(),
      totalPages: messages.totalPages, // ارسال تعداد کل صفحات
      totalItems: messages.totalDocs // ارسال تعداد کل آیتم‌ها
    })
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' })
  }
}
const closeTicket = async (req, res) => {
  try {
    const token = req.header('Authorization').split(' ')[1]
    if (!token) return res.status(401).send('Access Denied')

    const { ticketId } = req.body
    if (!ticketId) return res.status(400).send('Ticket ID is required')

    const ticket = await TicketModel.findById(ticketId)
    if (!ticket) return res.status(404).send('Ticket not found')

    ticket.status = 'Closed'
    await ticket.save()

    res.status(200).json({ message: 'Ticket has been closed successfully' })
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' })
  }
}

module.exports = { getAllTickets, addAdminMessageToTicket, getTicketMessages, closeTicket }
