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

// Counselor scope: backend hides every ticket whose type !== 'advise'.
const counselorPool = () => adminTickets.filter((t) => t.type === 'advise')

register('GET', endpoints.getCounselorTickets, ({ query }) => {
  let list = filterItems(counselorPool(), query, {
    type: 'eq',
    status: 'eq',
    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.showCounselorTicket, ({ params }) => ({
  success: true,
  message: 'OK',
  data: findOrThrow(counselorPool(), params.id),
}))

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

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