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

// Student scope: backend scopes results to the signed-in student. The mock
// pretends every ticket whose student is studentJane (id=100) belongs to "me".
const SELF_STUDENT_ID = 100

const myPool = () => adminTickets.filter((t) => t.studentId === SELF_STUDENT_ID)

register('GET', endpoints.getStudentTickets, ({ query }) => {
  const list = filterItems(myPool(), query, {
    type: 'eq',
    status: 'eq',
  })
  const { data: items, meta } = paginate(list, query)
  return { success: true, message: 'OK', data: items, meta }
})

register('GET', endpoints.getStudentTicketStats, ({ query }) => {
  const scoped = query.type ? myPool().filter((t) => t.type === query.type) : myPool()
  const countBy = (status) => scoped.filter((t) => t.status === status).length
  return {
    success: true,
    message: 'OK',
    data: {
      openTickets: countBy('open'),
      answeredTickets: countBy('answered'),
      closedTickets: countBy('closed'),
      all: scoped.length,
    },
  }
})

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

register('POST', endpoints.createStudentTicket, ({ data }) => {
  const me = myPool()[0]?.student || adminTickets[0].student
  const ticket = {
    id: makeId(),
    studentId: me.id,
    assignedToUserId: null,
    type: data.type || 'ticket',
    category: data.category || null,
    priority: data.priority || null,
    status: 'open',
    subject: data.subject || '',
    createdAt: isoNow(),
    media: [],
    student: me,
    assignee: null,
    messages: [
      {
        id: makeId(),
        ticketId: 0,
        senderId: me.id,
        message: data.message || '',
        createdAt: isoNow(),
        sender: me,
      },
    ],
  }
  ticket.messages[0].ticketId = ticket.id
  adminTickets.unshift(ticket)
  return {
    success: true,
    message: 'Ticket created.',
    data: {
      id: ticket.id,
      studentId: ticket.studentId,
      assignedToUserId: ticket.assignedToUserId,
      type: ticket.type,
      category: ticket.category,
      priority: ticket.priority,
      status: ticket.status,
      subject: ticket.subject,
      createdAt: ticket.createdAt,
      media: ticket.media,
    },
  }
})

register('POST', endpoints.sendStudentTicketMessage, ({ params, data }) => {
  const ticket = findOrThrow(myPool(), params.id)
  const me = ticket.student
  const message = {
    id: makeId(),
    ticketId: ticket.id,
    senderId: me.id,
    message: data.message || '',
    createdAt: isoNow(),
    sender: me,
  }
  ticket.messages = [...(ticket.messages || []), message]
  return { success: true, message: 'Message posted.', data: message }
})
