import { mount } from '@vue/test-utils'
import { describe, expect, it } from 'vitest'
import { createI18n } from 'vue-i18n'
import { createMemoryHistory, createRouter } from 'vue-router'

import zhCN from '@/i18n/locales/zh-CN'
import ReservationTaskQueue from '@/components/reservation/ReservationTaskQueue.vue'
import type { ReservationOrderTaskTimelineItem } from '@/types/reservation'

function createTaskQueueItem(overrides: Partial<ReservationOrderTaskTimelineItem> = {}): ReservationOrderTaskTimelineItem {
  return {
    task_id: '10001',
    task_type: 'NEW_BOOKING',
    task_subtype: 'NEW_BOOKING',
    task_status: 'PENDING_CONFIRM',
    card_name: 'New Booking',
    queue_sequence: 1,
    queue_participation: true,
    can_process: true,
    readonly_reason_code: null,
    source_message_id: '30001',
    source_subject: 'Booking Request',
    source_sender_summary: 'guest@example.test',
    source_received_at: '2026-07-08T03:00:00Z',
    external_conversation_id: null,
    conversation_message_count: 2,
    created_at: '2026-07-08T03:00:00Z',
    ...overrides,
  }
}

async function mountQueue(items: ReservationOrderTaskTimelineItem[]) {
  const i18n = createI18n({
    legacy: false,
    locale: 'zh-CN',
    messages: {
      'zh-CN': zhCN,
    },
  })
  const router = createRouter({
    history: createMemoryHistory(),
    routes: [
      { path: '/', component: { template: '<div />' } },
      { path: '/reservation/source-messages/:sourceMessageId/conversation', component: { template: '<div />' } },
    ],
  })
  await router.push('/')
  await router.isReady()

  return mount(ReservationTaskQueue, {
    props: {
      items,
      activeTaskId: '10001',
    },
    global: {
      plugins: [i18n, router],
      stubs: {
        RouterLink: {
          template: '<a><slot /></a>',
        },
      },
    },
  })
}

describe('ReservationTaskQueue', () => {
  it('opens the source conversation by source message id without external conversation id', async () => {
    const wrapper = await mountQueue([createTaskQueueItem()])

    expect(wrapper.text()).toContain('查看邮件会话')
    expect(wrapper.text()).not.toContain('接口待补')
  })

  it('shows readonly reason when a queued task cannot be processed', async () => {
    const wrapper = await mountQueue([
      createTaskQueueItem({
        can_process: false,
        readonly_reason_code: 'PREVIOUS_TASK_NOT_FINISHED',
      }),
    ])

    expect(wrapper.text()).toContain('不可处理')
    expect(wrapper.text()).toContain('前序任务未完成')
    expect(wrapper.text()).not.toContain('PREVIOUS_TASK_NOT_FINISHED')
  })
})
