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

const getUserTickets = 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 userId = decodedToken.id
    const { page = 1, limit = 10, search } = req.query // افزودن پارامترهای صفحه‌بندی به درخواست
    const filter = { user: userId }
    if (search) {
      filter.$or = [
        { title: { $regex: search, $options: 'i' } }
      ]
    }
    const options = {
      page: parseInt(page) || 1,
      limit: parseInt(limit) || 10,
      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 createTicket = 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 userId = decodedToken.id

    const { title } = req.body

    const newTicket = new TicketModel({
      title,
      user: userId
    })
    await newTicket.save()

    res.status(201).json(newTicket)
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' })
  }
}
const addUserMessageToTicket = 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 userId = decodedToken.id

    const { ticketId } = req.query
    const { text } = req.body
    const { file } = req.files
    let fileUrl = null
    if (file) {
      // اگر فایل ارسال شده است، آن را ذخیره کنید
      const uploadDir = path.join(__dirname, '../../../../storage/tickets')
      if (!fs.existsSync(uploadDir)) {
        fs.mkdirSync(uploadDir, { recursive: true })
      }

      const uniqueFileName = `${Date.now()}-${file.name}`
      const filePath = path.join(uploadDir, uniqueFileName)
      await fs.move(file.path, filePath)

      fileUrl = `/tickets/${uniqueFileName}`
    }
    const newMessage = new TicketMessageModel({
      text,
      senderType: 'User',
      senderId: userId,
      ticket: ticketId,
      file: fileUrl
    })
    await newMessage.save()

    const ticket = await TicketModel.findById(ticketId)
    if (!ticket) {
      return res.status(404).json({ error: 'Ticket not found' })
    }

    ticket.status = 'Customer Response'
    await ticket.save()
    const newMessageWithJalaliDate = {
      ...newMessage._doc,
      createdAt: jMoment(newMessage.createdAt).format('jYYYY-jMM-jDD HH:mm')
    }
    res.status(201).json(newMessageWithJalaliDate)
  } catch (error) {
    res.status(500).json({ error: 'Internal Server Error' })
  }
}
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,
      sort: { createdAt: -1 }
    }
    const messages = await TicketMessageModel.paginate({ ticket: ticketId }, options)
    const ticket = await TicketModel.findById(ticketId)
    ticket.new_message = false
    await ticket.save()
    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' })
  }
}
module.exports = { getUserTickets, createTicket, addUserMessageToTicket, getTicketMessages }
