import { api } from '../../api/client'
import { registerIslanderActionHandler } from './actionExecutor'


type CopyActionDeps = {
  personaId: string
  keywords: string[]
  onStartScan?: () => void
  onGenerateDraft?: (scanPostId: string) => void
  reload?: () => void
}

let deps: CopyActionDeps | null = null

export function setCopyActionDeps(next: CopyActionDeps | null) {
  deps = next
}

export function registerCopyIslanderActions() {
  registerIslanderActionHandler('startViralScan', async () => {
    if (!deps?.personaId) {
      return { action: { type: 'startViralScan' }, ok: false, detail: '請先選擇人設' }
    }
    try {
      await api.post(
        `/api/v1/personas/${encodeURIComponent(deps.personaId)}/viral-scan-jobs`,
        { keywords: deps.keywords.filter((k) => k.trim()) },
        { auth: true },
      )
      deps.onStartScan?.()
      deps.reload?.()
      return { action: { type: 'startViralScan' }, ok: true, detail: '已啟動爆款海巡背景任務' }
    } catch (e) {
      const message = e instanceof Error ? e.message : '啟動失敗'
      return { action: { type: 'startViralScan' }, ok: false, detail: message }
    }
  })

  registerIslanderActionHandler('generateCopyDraft', async (action) => {
    if (!deps?.personaId) {
      return { action, ok: false, detail: '請先選擇人設' }
    }
    if (action.type !== 'generateCopyDraft') {
      return { action, ok: false, detail: '動作類型錯誤' }
    }
    const scanPostId = action.scan_post_id?.trim()
    if (!scanPostId) {
      return { action, ok: false, detail: '缺少 scan_post_id' }
    }
    try {
      await api.post(
        `/api/v1/personas/${encodeURIComponent(deps.personaId)}/copy-drafts/generate`,
        { scan_post_id: scanPostId },
        { auth: true },
      )
      deps.onGenerateDraft?.(scanPostId)
      deps.reload?.()
      return { action, ok: true, detail: '已產出仿寫草稿' }
    } catch (e) {
      const message = e instanceof Error ? e.message : '產出失敗'
      return { action, ok: false, detail: message }
    }
  })

  registerIslanderActionHandler('navigateToPersona8D', async (_action, ctx: { navigate: (path: string) => void }) => {
    if (!deps?.personaId) {
      return { action: { type: 'navigateToPersona8D' }, ok: false, detail: '請先選擇人設' }
    }
    ctx.navigate(`/personas/${deps.personaId}#style-8d`)
    return { action: { type: 'navigateToPersona8D' }, ok: true, detail: '已前往 8D 對標區塊' }
  })
}