import { register } from '@/services/mock/registry'
import { endpoints } from '@/services/api/endpoints'
import { adminTickets, currentAdminUser } from '@/services/mock/fixtures/admin-tickets'
import {
  filterDateRange,
  filterItems,
  findOrThrow,
  isoNow,
  makeId,
  paginate,
  updateById,
} from '@/services/mock/helpers'

register('GET', endpoints.getTicketsList, ({ query }) => {
  let list = filterItems(adminTickets, query, {
    type: 'eq',
    status: 'eq',
    subject: (item, v) =>
      String(item.subject || '')
        .toLowerCase()
        .includes(String(v).toLowerCase()),
    userName: (item, v) =>
      String(item.student?.name || '')
        .toLowerCase()
        .includes(String(v).toLowerCase()),
  })
  list = filterDateRange(list, query)
  const { data: items, meta } = paginate(list, query)
  return {
    success: true,
    message: 'OK',
    data: items,
    meta,
  }
})

register('GET', endpoints.showTicket, ({ params }) => ({
  success: true,
  message: 'OK',
  data: findOrThrow(adminTickets, params.id),
}))

register('POST', endpoints.sendTicketMessage, ({ params, data }) => {
  const ticket = findOrThrow(adminTickets, params.id)
  const message = {
    id: makeId(),
    ticketId: ticket.id,
    senderId: currentAdminUser.id,
    message: data.message || '',
    createdAt: isoNow(),
    sender: currentAdminUser,
  }
  ticket.messages = [...(ticket.messages || []), message]
  ticket.status = 'answered'
  ticket.assignedToUserId = currentAdminUser.id
  ticket.assignee = currentAdminUser
  return {
    success: true,
    message: 'Message posted.',
    data: message,
  }
})

register('PATCH', endpoints.changeTicketStatus, ({ params, data }) => ({
  success: true,
  message: 'Ticket status updated.',
  data: updateById(adminTickets, params.id, { status: data.status }),
}))
