import { describe, expect, it } from 'vitest'

import { formatInteractiveQuestionAnswer, parseInteractiveMessage } from './interactiveMessage'

const questionBlock = `\`\`\`acw-question
{
  "version": 1,
  "id": "target_user",
  "title": "这个需求主要面向谁？",
  "description": "选择后我会补全场景。",
  "mode": "single",
  "options": [
    {
      "id": "admin",
      "label": "后台管理员",
      "summary": "负责配置和审核",
      "details": "更关注权限、批量操作和审计。"
    },
    {
      "id": "user",
      "label": "普通用户"
    }
  ],
  "allowCustom": true
}
\`\`\``

describe('interactiveMessage', () => {
  it('解析 acw-question 代码块并保留普通 Markdown', () => {
    const parsed = parseInteractiveMessage(`# 前置说明\n\n${questionBlock}`)

    expect(parsed.markdown).toBe('# 前置说明')
    expect(parsed.question?.id).toBe('target_user')
    expect(parsed.question?.options[0]).toMatchObject({
      id: 'admin',
      label: '后台管理员',
      summary: '负责配置和审核',
    })
  })

  it('非法 JSON 时回退为普通 Markdown', () => {
    const content = '```acw-question\n{ broken }\n```'
    const parsed = parseInteractiveMessage(content)

    expect(parsed.question).toBeNull()
    expect(parsed.markdown).toBe(content)
  })

  it('选项数量不合法时回退为普通 Markdown', () => {
    const content = `\`\`\`acw-question
{"version":1,"id":"q","title":"Q","mode":"single","options":[{"id":"a","label":"A"}]}
\`\`\``
    const parsed = parseInteractiveMessage(content)

    expect(parsed.question).toBeNull()
    expect(parsed.markdown).toBe(content)
  })

  it('格式化用户选择为稳定文本', () => {
    const parsed = parseInteractiveMessage(questionBlock)
    expect(parsed.question).not.toBeNull()

    const text = formatInteractiveQuestionAnswer({
      question: parsed.question!,
      selectedOptionIds: ['admin'],
      customText: '还需要导出日志',
    })

    expect(text).toContain('question_id: target_user')
    expect(text).toContain('- admin: 后台管理员 - 负责配置和审核')
    expect(text).toContain('还需要导出日志')
  })
})
